# Upstash Redis on Vercel Edge and Next.js

## Why REST here

Edge functions cannot hold TCP connections. The @upstash/redis SDK talks
HTTP, so there is no connection pool to warm, leak, or exhaust. This is
the intended client for Next.js API routes, middleware, and edge
functions.

## Setup

1. Add UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN in the Vercel
   project settings under Environment Variables.
2. Create one client at module scope:

import { Redis } from "@upstash/redis";

export const redis = Redis.fromEnv();

3. Import that shared client in your route handlers. Do not construct a
   new Redis inside each request handler.

## Batching on the edge

Auto-pipelining is on by default. This pattern fires one batched HTTP
request:

const [user, cart] = await Promise.all([
  redis.get("user:42"),
  redis.get("cart:42"),
]);

This pattern fires two separate requests:

const user = await redis.get("user:42");
const cart = await redis.get("cart:42");

Each REST call is billed, so the batched form is cheaper as well as
faster.

## Middleware note

Middleware runs on the edge on every request. A Redis call in middleware
is a billed command per request, so keep middleware reads to one batched
call or a single key, and cache aggressively.