by Devika

A connectionless, HTTP/REST-based Redis client for TypeScript designed for serverless functions, Cloudflare Workers, Next.js, and edge runtimes where TCP connections are unavailable.
This block provides @upstash/redis, a connectionless HTTP/REST-based Redis client for TypeScript. It communicates with Upstash's REST API instead of a raw TCP socket, making it suitable for serverless functions, Cloudflare Workers, Fastly Compute@Edge, and any edge runtime where persistent connections are unavailable. The typical buyer is a TypeScript developer deploying to a serverless or edge environment who needs Redis without a connection pool.
pkg/ - Core client logic: Redis class, pipeline, scripting, HTTP transport, error types, and all command implementationspkg/commands/ - One file per Redis command, plus a search/ sub-directory for vector/full-text search index supportpkg/commands/search/ - SearchIndex, schema builder s, and TypeScript helpers for Upstash Searchpkg/auto-pipeline.ts - Automatic pipeline batching wrapper around the Redis clientpkg/error.ts - UpstashError class exported as the public error typepkg/http.ts - Low-level HTTP transport that signs and sends REST requestspkg/index.ts - Package entry re-exporting error typespkg/pipeline.ts - Manual pipeline implementation for batching multiple commandspkg/redis.ts - Main Redis class with all command methodspkg/script.ts - Script helper for EVALSHA-with-fallback patternspkg/scriptRo.ts - Read-only variant of Scriptpkg/types.ts - Shared TypeScript types used across commandspkg/util.ts - Internal serialization/deserialization utilitiesplatforms/ - Platform-specific entry points: nodejs.ts, cloudflare.ts, fastly.tsversion.ts - Exports the VERSION constant (v1.37.0)tsup.config.ts - Build configuration (tsup, outputs CJS + ESM with .d.ts)package.json - Package manifesttsconfig.json - TypeScript compiler configurationSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 86e3d4dbd8b97070…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
npm install @upstash/redis
No native modules, no pod install, no Android linking, no expo prebuild required. The library is pure TypeScript with zero runtime dependencies and communicates exclusively over HTTP.
Copy the source/ directory into your project, e.g. src/vendor/upstash-redis/.
Ensure your tsconfig.json targets at minimum ES2017 and enables moduleResolution: "node16" or "bundler":
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true
}
}
Add path aliases if you want cleaner imports:
{
"compilerOptions": {
"paths": {
"@upstash/redis": ["./src/vendor/upstash-redis/platforms/nodejs.ts"]
}
}
}
Set the required environment variables. Create an Upstash Redis database at console.upstash.com and copy the REST URL and token:
UPSTASH_REDIS_REST_URL=https://<your-db>.upstash.io
UPSTASH_REDIS_REST_TOKEN=<your-token>
Load env vars via dotenv or your runtime's native mechanism before importing the client.
Build with tsup (already configured in tsup.config.ts) or integrate into your existing bundler. Run npx tsup from the source/ root to produce CJS + ESM artifacts in dist/.
import { Redis } from "./platforms/nodejs";
const redis = new Redis({
url: string; // UPSTASH_REDIS_REST_URL
token: string; // UPSTASH_REDIS_REST_TOKEN
automaticDeserialization?: boolean; // default true
});
The primary client class. Instantiate once per process and reuse. Every Redis command (get, set, hset, zadd, etc.) is available as an async method. Use this for all standard key-value, hash, sorted set, list, set, and stream operations against an Upstash REST endpoint.
import { UpstashError } from "./pkg/error";
class UpstashError extends Error {
constructor(message: string);
}
Thrown by the HTTP transport whenever Upstash returns a non-OK response or a Redis-level error. Catch this specifically to distinguish Redis errors from network errors in your application's error handling layer.
import { SearchIndex } from "./pkg/commands/search";
import type { SearchIndexParameters, CreateIndexParameters } from "./pkg/commands/search";
Provides a typed interface to Upstash's vector/full-text Search API. Use SearchIndex to create indexes, upsert documents, and run queries with schema-derived TypeScript types. Pair with the s schema builder to define strongly-typed field schemas at compile time.
import { s } from "./pkg/commands/search";
const schema = {
title: s.text(),
price: s.numeric(),
inStock: s.tag(),
};
Fluent schema builder for SearchIndex. Each call to s.text(), s.numeric(), or s.tag() produces a field descriptor that drives both the index creation payload and the TypeScript filter types inferred via InferFilterFromSchema.
Standard Redis data structure usage in a Node.js TypeScript service. Connect using environment variables and perform a mix of reads and writes.
import { Redis } from "./platforms/nodejs";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
async function main() {
// String
await redis.set("session:abc", JSON.stringify({ userId: 42 }), { ex: 3600 });
const session = await redis.get<{ userId: number }>("session:abc");
console.log(session?.userId); // 42
// Hash
await redis.hset("user:42", { name: "Alice", role: "admin" });
const name = await redis.hget<string>("user:42", "name");
console.log(name); // "Alice"
// Sorted set
await redis.zadd("leaderboard", { score: 1500, member: "Alice" });
const top = await redis.zrange("leaderboard", 0, 9, { rev: true });
console.log(top); // ["Alice"]
}
main();
Use a pipeline to send multiple commands in a single HTTP round-trip, reducing latency in serverless environments.
import { Redis } from "./platforms/nodejs";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
async function seedData() {
const pipeline = redis.pipeline();
pipeline.set("counter", 0);
pipeline.incr("counter");
pipeline.incr("counter");
pipeline.get("counter");
const results = await pipeline.exec<[string, number, number, number]>();
console.log(results); // ["OK", 1, 2, 2]
}
seedData();
Distinguish Upstash/Redis-level errors from unexpected runtime exceptions in a production service.
import { Redis } from "./platforms/nodejs";
import { UpstashError } from "./pkg/error";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL!,
token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});
async function safeGet(key: string): Promise<unknown> {
try {
return await redis.get(key);
} catch (err) {
if (err instanceof UpstashError) {
console.error("Redis error:", err.message);
return null;
}
throw err; // re-throw unexpected errors
}
}
safeGet("some:key").then(console.log);
Use the Cloudflare-specific platform entry to avoid Node.js built-ins that are unavailable in the Workers runtime.
// worker.ts (Cloudflare Workers)
import { Redis } from "./platforms/cloudflare";
export default {
async fetch(request: Request, env: { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string }) {
const redis = new Redis({
url: env.UPSTASH_REDIS_REST_URL,
token: env.UPSTASH_REDIS_REST_TOKEN,
});
const visits = await redis.incr("visits");
return new Response(`Visit count: ${visits}`, { status: 200 });
},
};
platforms/nodejs.ts - Node.js entry point; re-exports Redis configured for the Node.js fetch implementation.platforms/cloudflare.ts - Cloudflare Workers entry; uses the global fetch available in that runtime.platforms/fastly.ts - Fastly Compute@Edge entry; adapts the HTTP transport for the Fastly fetch API.pkg/redis.ts - Defines the Redis class, attaches all command methods, and wires the HTTP client.pkg/pipeline.ts - Collects queued commands and flushes them as a single batch request.pkg/auto-pipeline.ts - Wraps Redis to coalesce concurrent awaits into a pipeline automatically.pkg/http.ts - Sends signed HTTP requests to the Upstash REST endpoint and parses responses.pkg/error.ts - Declares UpstashError; the sole export of pkg/index.ts.pkg/script.ts - Script class for EVALSHA with automatic EVAL fallback on NOSCRIPT errors.pkg/scriptRo.ts - Read-only counterpart to Script using EVALSHA_RO.pkg/types.ts - Shared TypeScript interfaces and type aliases used by commands and the client.pkg/util.ts - Serialization helpers for encoding arguments and deserializing responses.pkg/commands/ - Individual command files (one per Redis command), each exporting a command class.pkg/commands/search/ - SearchIndex class, schema builder s, and related types for Upstash Search.version.ts - Single exported constant VERSION = "v1.37.0" used for telemetry headers.tsup.config.ts - Produces CJS and ESM bundles with declaration files for all three platform entries.url or token being undefined causes silent 401/404 errors. Fix: validate both values on startup with a guard like if (!url || !token) throw new Error(...).platforms/nodejs pulls in Node.js globals unavailable in Workers. Fix: always import from platforms/cloudflare in Worker scripts.automaticDeserialization surprises: by default the client JSON-parses all responses, so stored JSON strings become objects without an explicit JSON.parse. Fix: pass automaticDeserialization: false if you store raw strings and want them returned as-is.pipeline.exec() returns results in the same order commands were queued; forgetting a queued command shifts all subsequent indices. Fix: type the result tuple explicitly: exec<[string, number, number]>()."moduleResolution": "bundler" in tsconfig.json or explicitly point to the .mjs output.Upstash-Telemetry header with the SDK version and runtime. Fix: this is anonymous and cannot be disabled; ensure your CSP or egress rules do not block it.I have the Upstash Redis HTTP/REST client source code in `source/` and its integration guide in `USAGE.md`.
The upstream package is `@upstash/redis` (version v1.37.0).
Please integrate this Redis client into my existing project step-by-step:
1. Read `USAGE.md` and `source/pkg/redis.ts` to understand the Redis class constructor and available methods.
2. Identify the correct platform entry point for my runtime (Node.js → `source/platforms/nodejs.ts`, Cloudflare Workers → `source/platforms/cloudflare.ts`).
3. Add the required environment variables (`UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN`) to `.env` and validate them on startup.
4. Create a shared `src/lib/redis.ts` singleton that instantiates `Redis` once and exports it.
5. Replace any existing in-memory caching or session storage in my project with calls to the Redis singleton.
6. Add pipeline usage (`redis.pipeline()`) wherever multiple Redis calls are made in the same request handler.
7. Wrap all Redis calls with try/catch that catches `UpstashError` (from `source/pkg/error.ts`) separately from other errors.
8. Show me the final imports, the singleton file, and two updated route handlers as runnable TypeScript.
The source is licensed under the MIT License (see source/LICENSE if present, or the upstream repository). Upstream project: @upstash/redis by Upstash, Inc. Refer to the upstream repository for the full license text, changelog, and contribution guidelines.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free