Why Upstash Redis for Cloudflare Workers?
- Edge-native: HTTP-based connection perfect for Workers
- Global low latency: Access Redis from 300+ cities worldwide
- No cold starts: Instant execution at the edge
- Automatic scaling: Handles traffic spikes seamlessly
Prerequisites
1
Create Cloudflare Account
Sign up for a Cloudflare account
2
Install Wrangler CLI
Install the Cloudflare Workers CLI:
3
Create Upstash Redis Database
Create a Redis database on Upstash Console
Quick Start
Project Setup
1
Clone Example or Create New Project
2
Install Dependencies
Example: Counter Worker
This example implements a simple counter that increments on each request.Notice the import path:
@upstash/redis/cloudflare - This is important for Cloudflare Workers compatibility.Configuration
Add Environment Variables
You can configure environment variables in two ways:Option 1: wrangler.toml (Not Recommended for Production)
wrangler.toml
Option 2: Cloudflare Dashboard (Recommended)
1
Go to Workers Dashboard
Navigate to your Cloudflare Workers dashboard
2
Select Your Worker
Click on your Worker or create a new one
3
Add Environment Variables
Go to Settings > Variables and add:
UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN
Option 3: Wrangler CLI Secrets (Most Secure)
Development
Run Locally
1
Start Development Server
2
Test Your Worker
Open your browser at localhost:8787
Deploy to Cloudflare
*.workers.dev URL.
Advanced Examples
REST API with Routing
Edge Caching
Rate Limiting at the Edge
Session Management
TypeScript Support
For full TypeScript support, use the TypeScript template:Best Practices
Initialize Redis Client Inside Handler
Unlike traditional environments, Workers don’t maintain state between requests. Initialize the client in each request:Error Handling
Use Edge Location Data
Cloudflare provides request context with location data:Testing
Local Testing with Wrangler
Unit Testing
For unit testing Workers, see Cloudflare Workers testing documentation.Monitoring
View Logs
Add Custom Logging
Troubleshooting
Module not found: @upstash/redis/cloudflare
Module not found: @upstash/redis/cloudflare
Make sure you’re using the correct import path:Not:
Environment variables not accessible
Environment variables not accessible
Ensure variables are:
- Set in
wrangler.toml[vars] section, OR - Set in Cloudflare Dashboard, OR
- Set as secrets via
wrangler secret put
env parameter:Deployment fails
Deployment fails
Check your
wrangler.toml configuration:namemust be uniquemainmust point to your entry filecompatibility_dateshould be recent
Next Steps
AWS Lambda
Deploy Redis with AWS Lambda
Next.js
Integrate Redis with Next.js
Basic Usage
Learn more Redis operations
Cloudflare Docs
Cloudflare Workers documentation