LOG IN SIGN UP
Documentation

Local variables in VCL

  Last updated February 08, 2017

Fastly VCL supports variables for storing temporary values during request processing.

Declaring a variable

Variables must be declared before they are used, usually at the beginning of the function before any statements. They can only be used in the same function where they are declared. Variables with the same name in different function blocks are unrelated variables.

Variables start with var. and their names consist of characters in the set [A-Za-z0-9._-]. (: is explicitly disallowed.) The declaration syntax is:

declare local var.<name> <type>;

Variable types

Variables can be of the following types:

Declared variables are initialized to the zero value of the type:

Use

Boolean variables

Boolean assignments support boolean variables on the right-hand side as well as BOOL-returning functions, conditional expressions, and the true and false constants. For example:

declare local var.boolean BOOL;

# BOOL assignment with RHS variable
set var.boolean = true;
set req.esi = var.boolean;
set resp.http.Bool = if(req.esi, "y", "n");

# BOOL assignment with RHS function
set var.boolean = http_status_matches(resp.status, "200,304");

# BOOL assigment with RHS conditional
set var.boolean = (req.url == "/");

# non-NULL-ness check, like 'if (req.http.Foo) { ... }'
set var.boolean = (req.http.Foo);

Numeric variables

Numeric assignment and comparison support numeric variables (anything except STRING or BOOL) on the right-hand side, including conversion in both directions between FLOAT and INTEGER types, rounding to the nearest integer in the FLOAT to INTEGER case. For example:

declare local var.integer INTEGER;
declare local var.float FLOAT;

# Numeric assignment with RHS variable and
# implicit string conversion for header
set var.integer = req.bytes_read;
set var.integer -= req.body_bytes_read;
set resp.http.VarInteger = var.integer;

# Numeric comparison with RHS variable
set resp.http.VarIntegerOK = if(req.header_bytes_read == var.integer, "y", "n");

Invalid conditions or domain errors like division by 0 will set fastly.error.

String variables

String assignments support string concatenation on the right-hand side. For example:

declare local var.restarted STRING;

# String concatenation on RHS
set var.restarted = "Request " if(req.restarts > 0, "has", "has not") " restarted.";

Time variables

Time variables support both relative and absolute times. For example:

declare local var.time TIME;
declare local var.rtime RTIME;

set req.grace = 72s;
set var.rtime = req.grace;
set resp.http.VarRTime = var.rtime;

set var.time = std.time("Fri, 10 Jun 2016 00:02:12 GMT", now);
set var.time -= var.rtime;
# implicit string conversion for header
set resp.http.VarTime = var.time;

Back to Top