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 greetingsStep-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:
npm install @upstash/redis
Replace src/index.js with the following:
Run locally
Runwrangler 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/