Worker Variables
Zaraz Worker Variables are a powerful type of variable that you can configure and then use in your actions and triggers. Unlike string and masked variables, Worker Variables are dynamic. This means you can use a Cloudflare Worker to determine the value of the variable, allowing you to use them for countless purposes. For example:
- A Worker Variable that calculates the sum of all products in the cart
- A Worker Variable that takes a cookie, makes a request to your backend, and returns the User ID
- A Worker Variable that hashes a value before sending it to a third-party vendor
To use a Worker Variable, you first need to create a new Cloudflare Worker. You can do this through the Cloudflare dashboard or by using Wrangler.
To create a new Worker in the Cloudflare dashboard:
- Log in to the Cloudflare dashboard ↗.
- Go to Workers & Pages and select Create application.
- Give a name to your Worker and select Deploy.
- Select Edit code.
You have now created a basic Worker that responds with “Hello world.” If you use this Worker as a Variable, your Variable will always output “Hello world.” The response body coming from your Worker will be the value of your Worker Variable. To make this Worker useful, you will usually want to use information coming from Zaraz, which is known as the Zaraz Context.
Zaraz forwards the Zaraz Context object to your Worker as a JSON payload with a POST request. You can access any property like this:
Keep reading for more complete examples of different use cases or refer to Zaraz Context.
Once your Worker is published, configuring a Worker Variable is easy.
- Log in to the Cloudflare dashboard ↗.
- Go to Zaraz > Tools configuration > Variables.
- Click Create variable.
- Give your variable a name, choose Worker as the Variable type, and select your newly created Worker.
- Save your variable.
Now that your Worker Variable is configured, you can use it in your actions and triggers.
To use your Worker Variable:
- Log in to the Cloudflare dashboard ↗, and select your account and domain.
- Go to Zaraz > Tools configuration > Tools.
- Click Edit next to a tool that you have already configured.
- Select an action or add a new one.
- Click on the plus sign at the right of the text fields.
- Select your Worker Variable from the list.
Assuming we are sending a list of products in a cart, like this:
Calculating the sum can be done like this:
Zaraz exposes all cookies automatically under the system.cookies
object, so they are always available. Accessing the cookie and using it to query your backend might look like this:
Assuming you’re sending a value that your want to hash, for example, an email address:
You can access this property and hash it like this: