Database Setup

Create a Redis database using Upstash Console or Upstash CLI.

Project Setup

We will use C3 (create-cloudflare-cli) command-line tool to create our application. You can open a new terminal window and run C3 using the prompt below.
npm create cloudflare@latest -- upstash-redis-worker
This will create a new Cloudflare Workers project:
➜  npm create cloudflare@latest -- upstash-redis-worker

> npx
> create-cloudflare upstash-redis-worker


─────────────────────────────────────────────────────────────────────────────────────────────────
👋 Welcome to create-cloudflare v2.50.8!
🧡 Let's get started.
📊 Cloudflare collects telemetry about your usage of Create-Cloudflare.

Learn more at: https://github.com/cloudflare/workers-sdk/blob/main/packages/create-cloudflare/telemetry.md
─────────────────────────────────────────────────────────────────────────────────────────────────

╭ Create an application with Cloudflare Step 1 of 3

├ In which directory do you want to create your application?
│ dir ./upstash-redis-worker

├ What would you like to start with?
│ category Hello World example

├ Which template would you like to use?
│ type Worker only

├ Which language do you want to use?
│ lang TypeScript

├ Copying template files
│ files copied to project directory

├ Updating name in `package.json`
│ updated `package.json`

├ Installing dependencies
│ installed via `npm install`

╰ Application created 

...

────────────────────────────────────────────────────────────
🎉  SUCCESS  Application created successfully!
We will also install the Upstash Redis SDK to connect to Redis.
npm install @upstash/redis

The Code

Here is a Worker template to configure and test Upstash Redis connection.
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 }));
  },
};

Configure Credentials

Navigate to Upstash Console and copy/paste your UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_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 npx wrangler dev Deploy your function to Cloudflare with npx wrangler deploy The endpoint of the function will be provided to you, once the deployment is done.

Advanced Usage: TCP with Durable Objects

The basic example above uses the @upstash/redis HTTP client, which is optimal for most use cases. However, for specific scenarios, you can leverage TCP connection and Cloudflare Durable Objects. Use TCP with Durable Objects when:
  • Your traffic is concentrated in a single region where your Upstash Redis primary is located
  • You have predictable, region-specific workloads
Stick with HTTP client when:
  • You have a global audience (recommended for most applications)
  • Your traffic patterns are distributed across multiple regions
  • You want simpler deployment and configuration
To get started, first install the ioredis package for TCP connections:
npm install ioredis
Then, define the durable object class:
import { DurableObject } from "cloudflare:workers";
import Redis from "ioredis";

export class RedisDurableObject extends DurableObject<Env> {
  public client: Redis;

  constructor(ctx: DurableObjectState, env: Env) {
    // Required, as we're extending the base class.
    super(ctx, env);
    this.client = new Redis(env.REDIS_URL);
  };

  getRedis(): Redis {
    return this.client;
  };
};
Next, update your wrangler.toml to include the Durable Object class:
[[durable_objects]]
name = "REDIS_CLIENT"
class_name = "RedisDurableObject"

[[migrations]]
tag = "v1"
new_classes = ["RedisDurableObject"]
Finally, update your worker code to use the Durable Object:
export default {
  async fetch(request, env, ctx) {
    const id = env.REDIS_CLIENTS.idFromName("client");
    const clientStub = env.REDIS_CLIENTS.get(id);
    const redis = clientStub.getRedis();

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

    return new Response(JSON.stringify({ count }));
  }
};
With this approach, the TCP redis client will be shared across worker invocations, allowing for efficient connection reuse. If you want to have a redis client per region, you can use idFromName with a region-specific name, like:
const id = env.REDIS_CLIENTS.idFromName(`${request.cf?.colo || "unknown-region"}`)

Repositories

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