An HTTP/REST based Redis client built on top of Upstash REST API.
@upstash/redis is an HTTP/REST-based Redis client built specifically for serverless and edge computing environments. Unlike traditional Redis clients that rely on persistent TCP connections, this package uses Upstash's REST API to communicate with Redis over HTTP. This architectural choice eliminates connection pooling issues, cold start penalties, and timeout problems that plague TCP-based clients in short-lived execution contexts like AWS Lambda, Cloudflare Workers, or Vercel Edge Functions.
The package maintains API compatibility with standard Redis commands while adapting them to a connectionless paradigm. You get familiar methods like set, get, hset, lpush, and sadd, but each operation is a discrete HTTP request. This trade-off adds minor latency compared to persistent connections but delivers reliability and simplicity in environments where maintaining long-lived connections is impractical or impossible.
With over 1.5 million weekly downloads, @upstash/redis has become the de facto choice for developers building stateful applications on serverless platforms. It's particularly popular in the Next.js and Remix ecosystems where developers need caching, session management, or rate limiting without managing connection lifecycle. The package is TypeScript-first, production-ready (GA status), and supports execution in Node.js, Deno, browsers, and WebAssembly runtimes.
The client requires an Upstash Redis database, which provides the REST API endpoint. Upstash offers a generous free tier and scales automatically, eliminating infrastructure management. This makes @upstash/redis a complete solution: the client handles the protocol, Upstash handles the Redis instance, and you focus on application logic.
import { Redis } from '@upstash/redis';
// Initialize with auto-loaded environment variables
// Expects UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN
const redis = Redis.fromEnv();
// Rate limiter: 10 requests per minute per IP
async function checkRateLimit(ip: string): Promise<boolean> {
const key = `rate:${ip}`;
const requests = await redis.incr(key);
if (requests === 1) {
await redis.expire(key, 60);
}
return requests <= 10;
}
// Cache API response with 5-minute TTL
async function getCachedUser(userId: string) {
const cacheKey = `user:${userId}`;
let user = await redis.get<{ name: string; email: string }>(cacheKey);
if (!user) {
user = await fetchUserFromDB(userId);
await redis.set(cacheKey, user, { ex: 300 });
}
return user;
}
// Leaderboard with sorted sets
async function updateScore(playerId: string, score: number) {
await redis.zadd('leaderboard', { score, member: playerId });
const topTen = await redis.zrange('leaderboard', 0, 9, { rev: true, withScores: true });
return topTen;
}
// Session storage with hash
async function saveSession(sessionId: string, data: Record<string, string>) {
await redis.hset(`session:${sessionId}`, data);
await redis.expire(`session:${sessionId}`, 86400);
}
async function fetchUserFromDB(userId: string) {
return { name: 'Alice', email: 'alice@example.com' };
}API Rate Limiting: Implement sliding window or token bucket rate limiters using Redis counters and expiration. Perfect for serverless API routes in Next.js or Express where each function invocation needs to check/increment request counts without maintaining state between invocations.
Session Storage for Edge Applications: Store user sessions in Redis from Cloudflare Workers or Vercel Edge Middleware. The connectionless model means every edge location can access session data without managing connection pools across distributed PoPs.
Feature Flag Management: Store and retrieve feature flags with sub-100ms latency from serverless functions. Use Redis hashes to organize flags by environment or user segment, enabling real-time feature rollouts without redeploying code.
Caching Computed Data: Cache expensive database queries or API responses in serverless functions. Set TTLs on cached values and let Redis handle expiration automatically, reducing downstream load and improving response times.
Leaderboard and Real-time Counters: Use Redis sorted sets (zadd, zrange) to maintain leaderboards or counters that multiple serverless functions update concurrently. Ideal for analytics dashboards, game scores, or social media metrics aggregated from distributed events.
npm install @upstash/redispnpm add @upstash/redisbun add @upstash/redis