Use Redis in Cloudflare Workers

Use Redis in Cloudflare Workers

·

2 min read

This tutorial showcases using Redis with REST API in Cloudflare Workers. We will write a sample edge function (Cloudflare Workers) which will show a custom greeting depending on the location of the client. We will load the greeting message from Redis so you can update it without touching the code.

Why Upstash?

  • Cloudflare Workers does not allow TCP connections. Upstash provides REST API on top of the Redis database.
  • Upstash is a serverless offering with per-request pricing which fits for edge and serverless functions.

Step-1: Create Redis Database

Create a free database from Upstash Console. Find your REST token in the database details page in the console. Copy the endpoint together with read-only token.

Connect your database with redis-cli and add some greetings

usw1-selected-termite-30690.upstash.io:30690> set GB "Ey up?"
OK
usw1-selected-termite-30690.upstash.io:30690> set US "Yo, what’s up?"
OK
usw1-selected-termite-30690.upstash.io:30690> set TR "Naber dostum?"
OK
usw1-selected-termite-30690.upstash.io:30690> set DE "Was ist los?"

Step-2: Edge Function

Probably the better way to work with Cloudflare Workers is to use Wrangler. But to keep this example simple, we will use Cloudflare Workers Playground. Check and run the code here.

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  let country = new Map(request.headers).get("cf-ipcountry");
  let url = `https://usw1-selected-termite-30690.upstash.io/get/${country}?_token=AnfiASQgNWQzYmYzMDYtZTJkOS00YWQxLTlhZDAtZmUyOTc5ZGVlOTNlrtzXPqVS39LBiT81oCue0Bal1BuC2CnlMhOJX9Odts4=`;
  let res = await fetch(url);
  let restext = await res.text();
  let greeting = await JSON.parse(restext);
  return greeting.result ? new Response(greeting.result) : new Response("Hello!");
}

The code tries to find out the user's location checking the "cf-ipcountry" header. Then it loads the correct greeting for that location using the Redis REST API.

Coming Soon: Global Database

The above example runs the code at the edge locations which is closest to your user. But it also accesses the Redis database which is at one specific region (us-west-2 in this example). Soon, Upstash is going to announce the Global Database which is replicated to multiple regions all over the world. The endpoint of the global database will point to the region that is closest to the client, just like the edge function itself. So the latency to your Redis database will be minimized globally.