Skip to main content

Get Started with Cloudflare Workers

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.

See 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.
  • Upstash Global database provides low latency all over the world.

Step-1: Create Redis Database

Create a free Global database from Upstash Console. Find your REST URL and token in the database details page in the console. Copy them.

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

The best way to work with Cloudflare Workers is to use Wrangler. After installing and configuring wrangler, create a folder for your project inside the folder run: wrangler init

It will create wrangler.toml. Copy and paste your account id to the toml which is logged by wrangler.

Paste the Upstash REST URL and token to the toml as below:

name = "using-cloudflare-workers"
type = 'webpack'
account_id = 'd7a1e25ed96722937c'
route = ''
zone_id = ''
usage_model = ''
workers_dev = true
target_type = "webpack"

[vars]
UPSTASH_REDIS_REST_TOKEN = "AX_sASQgODM5ZjExZGEtMmI3Mi00Mjcwk3NDIxMmEwNmNkYjVmOGVmZTk5MzQ="
UPSTASH_REDIS_REST_URL = "https://us1-merry-macaque-31458.upstash.io/"

Init a node project running: npm init

Install upstash-redis: npm install @upstash/redis

Add the index.js as below:

import { Redis } from '@upstash/redis/cloudflare'

const redis = Redis.fromEnv()

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

async function handleRequest(request) {
let country = new Map(request.headers).get("cf-ipcountry");
let greeting = await redis.get(country);
return greeting ? new Response(greeting) : 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.

Build and Deploy

Build and deploy your app to Cloudflare by running: wrangler publish

The url of your app will be logged: https://using-cloudflare-workers.upsdev.workers.dev/

Typescript Example

We also have a complete typescript example available here. It's a little bit more complicated because it uses the newer modules syntax and requires a build step, but it will get you started instantly if you want to use typescript.