generated from mintlify/starter
-
Notifications
You must be signed in to change notification settings - Fork 76
fix: update cf redis quickstart #508
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
CahidArda
wants to merge
2
commits into
main
Choose a base branch
from
DX-2040-update-cf-quickstarts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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 | ||
|
||
|
@@ -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. | ||
|
@@ -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 })); | ||
}, | ||
}; | ||
|
@@ -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) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.