Skip to main content

Upstash Redis in Cloudflare Workers

Database Setup

Create a Redis database using Upstash Console or Upstash CLI. Select the global to minimize the latency from all edge locations. Copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN for the next steps.

Project Setup

We will use Wrangler 2 for deployment, so please install (or upgrade) Wrangler 2.

Create a folder for your project and run wrangler init. You can select either js or ts. `

➜  quickstart-cloudflare-workers wrangler init
⛅️ wrangler 2.0.7
-------------------
Using npm as package manager.
✨ Created wrangler.toml
Would you like to use git to manage this Worker? (y/n)
✨ Initialized git repository
No package.json found. Would you like to create one? (y/n)
✨ Created package.json
Would you like to use TypeScript? (y/n)
Would you like to create a Worker at src/index.js? (y/n)
✨ Created src/index.js

Install dependencies: npm install @upstash/redis

The Code

If you selected js update src/index.js as below:

import { Redis } from "@upstash/redis/cloudflare";

export default {
async fetch(_request, env) {
const redis = Redis.fromEnv(env);

const count = await redis.incr("counter");

return new Response(
JSON.stringify({ count }),
);
},
};

If you selected ts update src/index.ts as below:

import { Redis } from "@upstash/redis/cloudflare";

export interface Env {
UPSTASH_REDIS_REST_URL: string;
UPSTASH_REDIS_REST_TOKEN: string;
}

export default {
async fetch(
_request: Request,
env: Env,
_ctx: ExecutionContext,
): Promise<Response> {
const redis = Redis.fromEnv(env);
const count = await redis.incr("counter");
return new Response(JSON.stringify({ count }));
},
};

Copy/paste your REST URL and TOKEN to your wrangler.toml as below.

[vars]
UPSTASH_REDIS_REST_URL="REPLACE_HERE"
UPSTASH_REDIS_REST_TOKEN="REPLACE_HERE"

Test and Deploy

You can test the function locally with wrangler dev

Deploy your function to Cloudflare with wrangler publish

The endpoint of the function will be printed.

Repo

Javascript: https://github.com/upstash/upstash-redis/tree/main/examples/cloudflare-workers

Typescript: https://github.com/upstash/upstash-redis/tree/main/examples/cloudflare-workers-with-typescript

Wrangler 1: https://github.com/upstash/upstash-redis/tree/main/examples/cloudflare-workers-with-wrangler-1