Why Upstash Redis for Next.js?
- Edge-ready: Works in Edge Runtime and Serverless Functions
- Server Components: Native support for React Server Components
- Fast: HTTP-based for quick cold starts on Vercel
- Simple: No connection pooling required
- Flexible: Use in API routes, Server Actions, or Server Components
Prerequisites
Create Upstash Redis Database
Create a database on Upstash Console
App Router (Next.js 13+)
Server Component Example
Server Components can directly access Redis without API routes.API Route Example
Server Actions
Server Actions provide a simple way to mutate data from Client Components.Pages Router
API Routes
Server-Side Rendering (SSR)
pages/index.tsx
Advanced Examples
Caching with Revalidation
app/posts/[id]/page.tsx
Rate Limiting Middleware
middleware.ts
Session Management
lib/session.ts
app/api/auth/login/route.ts
Real-time View Counter
app/blog/[slug]/page.tsx
app/blog/[slug]/ViewCounter.tsx
Best Practices
1. Initialize Client Once
Create a shared Redis instance:lib/redis.ts
2. Type Safety
Use TypeScript generics for type-safe operations:3. Error Handling
4. Caching Strategy
Implement cache-aside pattern:Deployment
Vercel
Add Environment Variables
In your Vercel project settings, add:
UPSTASH_REDIS_REST_URLUPSTASH_REDIS_REST_TOKEN
Other Platforms
Upstash Redis works on any platform that supports Next.js:- Netlify
- AWS Amplify
- Railway
- Render
Next Steps
AWS Lambda
Deploy with AWS Lambda
Cloudflare Workers
Use Redis at the edge
Basic Usage
Learn more Redis operations
GitHub Examples
More Next.js examples