Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion mint.json
Original file line number Diff line number Diff line change
Expand Up @@ -771,7 +771,6 @@
"group": "Support",
"pages": [
"redis/help/support",
"redis/help/prosupport",
"redis/help/sla",
"redis/help/uptime",
"redis/help/legal",
Expand Down
217 changes: 158 additions & 59 deletions redis/quickstarts/cloudflareworkers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ title: " Cloudflare Workers"
### Database Setup

Create a Redis database using [Upstash Console](https://console.upstash.com) or
[Upstash CLI](https://github.com/upstash/cli). Select the global to minimize the
latency from all edge locations.
[Upstash CLI](https://github.com/upstash/cli).

### Project Setup

Expand All @@ -15,48 +14,65 @@ We will use **C3 (create-cloudflare-cli)** command-line tool to create our appli
<CodeGroup>

```shell npm
npm create cloudflare@latest
npm create cloudflare@latest -- upstash-redis-worker
```

```shell yarn
yarn create cloudflare@latest
yarn create cloudflare upstash-redis-worker
```

```shell pnpm
pnpm create cloudflare upstash-redis-worker
```

</CodeGroup>

This will install the `create-cloudflare` package, and lead you through setup. C3 will also install Wrangler in projects by default, which helps us testing and deploying the application.
This will create a new Cloudflare Workers project:

```text
➜ npm create cloudflare@latest
Need to install the following packages:
[email protected]
Ok to proceed? (y) y
➜ 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.

using create-cloudflare version 2.1.0
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 ./cloudflare_starter
│ dir ./upstash-redis-worker
├ What type of application do you want to create?
type "Hello World" Worker
├ What would you like to start with?
category Hello World example
Do you want to use TypeScript?
yes typescript
Which template would you like to use?
type Worker only
├ Copying files from "hello-world" template
├ Which language do you want to use?
│ lang TypeScript
Do you want to use TypeScript?
yes typescript
Copying template files
files copied to project directory
Retrieving current workerd compatibility date
compatibility date 2023-08-07
Updating name in `package.json`
updated `package.json`
Do you want to use git for version control?
yes git
Installing dependencies
installed via `npm install`
╰ Application created
╰ Application created

...

────────────────────────────────────────────────────────────
🎉 SUCCESS Application created successfully!
```

We will also install the **Upstash Redis SDK** to connect to Redis.
Expand Down Expand Up @@ -98,9 +114,7 @@ import { Redis } from "@upstash/redis/cloudflare";
export default {
async fetch(request, env, ctx) {
const redis = Redis.fromEnv(env);

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

return new Response(JSON.stringify({ count }));
},
};
Expand All @@ -110,60 +124,145 @@ export default {

### Configure Credentials

There are two methods for setting up the credentials for Upstash Redis client. The recommended way is to use Cloudflare Upstash Integration. Alternatively, you can add the credentials manually.
Navigate to [Upstash Console](https://console.upstash.com) and copy/paste your `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` to your `wrangler.toml` as below.

#### Using the Cloudflare Integration
<CodeGroup>

Access to the [Cloudflare Dashboard](https://dash.cloudflare.com) and login with the same account that you've used while setting up the Worker application. Then, navigate to **Workers & Pages > Overview** section on the sidebar. Here, you'll find your application listed.
```yaml wrangler.toml
[vars]
UPSTASH_REDIS_REST_URL="REPLACE_HERE"
UPSTASH_REDIS_REST_TOKEN="REPLACE_HERE"
```

<Frame>
<img src="/img/cloudflare-integration/overview.png" />
</Frame>
```yaml wrangler.jsonc
{
"vars": {
"UPSTASH_REDIS_REST_URL": "REPLACE_HERE",
"UPSTASH_REDIS_REST_TOKEN": "REPLACE_HERE"
}
}
```

Clicking on the application will direct you to the application details page, where you can perform the integration process. Switch to the **Settings** tab in the application details, and proceed to **Integrations** section. You will see various Worker integrations listed. To proceed, click the **Add Integration** button associated with the Upstash Redis.
</CodeGroup>

<Frame>
<img src="/img/cloudflare-integration/redis-add-integration.png" />
</Frame>
### Test and Deploy

On the Integration page, connect to your Upstash account. Then, select the related database from the dropdown menu. Finalize the process by pressing Save button.
You can test the function locally with `npx wrangler dev`

<Note>
Please don't make any changes in the secret names on the **Configure secrets**
step. These credentials will be automatically picked up by
`Redis.fromEnv(env)` line in the code as `UPSTASH_REDIS_REST_URL` and
`UPSTASH_REDIS_REST_TOKEN`.
</Note>
Deploy your function to Cloudflare with `npx wrangler deploy`

<Frame>
<img src="/img/cloudflare-integration/redis-credentials.png" />
</Frame>
The endpoint of the function will be provided to you, once the deployment is done.

#### Setting up Manually
## Advanced Usage: TCP with Durable Objects

Navigate to [Upstash Console](https://console.upstash.com) and copy/paste your `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` to your `wrangler.toml` as below.
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](https://developers.cloudflare.com/durable-objects/).

```yaml
[vars]
UPSTASH_REDIS_REST_URL="REPLACE_HERE"
UPSTASH_REDIS_REST_TOKEN="REPLACE_HERE"
**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:

```bash
npm install ioredis
```

### Test and Deploy
Then, define the durable object class:

You can test the function locally with `npx wrangler dev`
<CodeGroup>

Deploy your function to Cloudflare with `npx wrangler deploy`
```ts src/index.ts
import { DurableObject } from "cloudflare:workers";
import Redis from "ioredis";

The endpoint of the function will be provided to you, once the deployment is done.
export class RedisDurableObject extends DurableObject<Env> {
public client: Redis;

### Repo
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;
};
};
```

</CodeGroup>

Next, update your `wrangler.toml` to include the Durable Object class:

<CodeGroup>

```yaml wrangler.toml
[[durable_objects]]
name = "REDIS_CLIENT"
class_name = "RedisDurableObject"

[[migrations]]
tag = "v1"
new_classes = ["RedisDurableObject"]
```

```yaml wrangler.jsonc
{
"durable_objects": {
"bindings": [
{
"name": "REDIS_CLIENT",
"class_name": "RedisDurableObject"
}
]
},
"migrations": [
{
"tag": "v1",
"new_classes": ["RedisDurableObject"]
}
]
}
```

</CodeGroup>

Finally, update your worker code to use the Durable Object:

<CodeGroup>

```ts src/index.ts
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 }));
}
};
```

</CodeGroup>

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:
```ts
const id = env.REDIS_CLIENTS.idFromName(`${request.cf?.colo || "unknown-region"}`)
```

## Repositories

Javascript:
[https://github.com/upstash/upstash-redis/tree/main/examples/cloudflare-workers](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](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](https://github.com/upstash/upstash-redis/tree/main/examples/cloudflare-workers-with-wrangler-1)