Skip to main content
This guide demonstrates how to use Upstash Redis in Next.js applications, covering both App Router and Pages Router patterns, Server Components, API Routes, and Server Actions.

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

1

Create Next.js App

2

Install Upstash Redis

3

Create Upstash Redis Database

Create a database on Upstash Console
4

Add Environment Variables

Create .env.local file:

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
Use it throughout your app:

2. Type Safety

Use TypeScript generics for type-safe operations:

3. Error Handling

4. Caching Strategy

Implement cache-aside pattern:

Deployment

Vercel

1

Add Environment Variables

In your Vercel project settings, add:
  • UPSTASH_REDIS_REST_URL
  • UPSTASH_REDIS_REST_TOKEN
2

Deploy

Other Platforms

Upstash Redis works on any platform that supports Next.js:
  • Netlify
  • AWS Amplify
  • Railway
  • Render
Just add the environment variables to your platform’s settings.

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