Use Redis in Cloudflare Workers
This tutorial showcases using Redis with REST API in 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
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
Choose yes
to create package.json, no
to typescript and yes
to create a
worker in src/index.js.
It will create wrangler.toml
, package.json
and src/index.js
.
Append the Upstash REST URL and token to the toml as below:
Install upstash-redis: npm install @upstash/redis
Replace src/index.js
with the following:
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.
Run locally
Run wrangler dev
and open your browser at
localhost:8787.
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.upstash.workers.dev/
Typescript example
We also have a typescript example, available here.