Skip to main content
The Redis class is the main entry point for interacting with Upstash Redis. It provides methods for all Redis commands and supports both direct instantiation and environment-based configuration.

Constructor

With Configuration Object

Create a new Redis client by providing connection credentials.
import { Redis } from '@upstash/redis';

const redis = new Redis({
  url: '<UPSTASH_REDIS_REST_URL>',
  token: '<UPSTASH_REDIS_REST_TOKEN>'
});
config
RedisConfigNodejs
required
Configuration object for the Redis client

With Custom Requester

Create a Redis client with a custom HTTP requester implementation.
import { Redis, Requester, UpstashRequest, UpstashResponse } from '@upstash/redis';

const customRequester: Requester = {
  request: async <TResult>(req: UpstashRequest): Promise<UpstashResponse<TResult>> => {
    // Custom request implementation
    // ...
  }
};

const redis = new Redis(customRequester);
requester
Requester
required
Custom requester implementation

Static Methods

fromEnv()

Create a Redis instance from environment variables.
const redis = Redis.fromEnv();
This method automatically loads connection credentials from:
  • UPSTASH_REDIS_REST_URL or KV_REST_API_URL (fallback for Vercel KV)
  • UPSTASH_REDIS_REST_TOKEN or KV_REST_API_TOKEN (fallback for Vercel KV)
config
Omit<RedisConfigNodejs, 'url' | 'token'>
Optional configuration (all options except url and token)
redis
Redis
A configured Redis instance
const redis = Redis.fromEnv({
  enableAutoPipelining: false,
  latencyLogging: true
});

Properties

readYourWritesSyncToken

Get or set the sync token for read-your-writes consistency.
// Get current sync token
const token = redis.readYourWritesSyncToken;

// Set sync token
redis.readYourWritesSyncToken = 'your-sync-token';
readYourWritesSyncToken
string | undefined
The current sync token

Instance Methods

pipeline()

Create a new pipeline to batch multiple commands.
const pipeline = redis.pipeline();
pipeline.set('key1', 'value1');
pipeline.set('key2', 'value2');
pipeline.get('key1');

const results = await pipeline.exec();
// results: ['OK', 'OK', 'value1']
pipeline
Pipeline
A new Pipeline instance for batching commands
See Pipeline for full documentation.

multi()

Create a transaction (MULTI/EXEC) to execute commands atomically.
const transaction = redis.multi();
transaction.set('key1', 'value1');
transaction.set('key2', 'value2');
transaction.get('key1');

const results = await transaction.exec();
// All commands executed atomically
multi
Pipeline
A new Pipeline instance configured for atomic execution

createScript()

Create a Lua script that can be executed efficiently using EVALSHA.
const script = redis.createScript<string>(
  'return ARGV[1];'
);

const result = await script.eval([], ['Hello World']);
// result: 'Hello World'
script
string
required
The Lua script to execute
opts
{ readonly?: boolean }
Script options
script
Script<TResult> | ScriptRO<TResult>
A Script or ScriptRO instance depending on the readonly option
See Script for full documentation.

use()

Wrap middleware around the HTTP client for custom request/response handling.
redis.use(async (request, next) => {
  console.log('Making request:', request);
  const response = await next(request);
  console.log('Received response:', response);
  return response;
});
middleware
(request: UpstashRequest, next: (req: UpstashRequest) => Promise<UpstashResponse<TResult>>) => Promise<UpstashResponse<TResult>>
required
Middleware function to wrap around requests

Command Methods

The Redis class provides methods for all Redis commands. Here are some commonly used examples:

String Commands

// SET
await redis.set('key', 'value');
await redis.set('key', 'value', { ex: 60 }); // with expiration

// GET
const value = await redis.get('key');

// MGET
const values = await redis.mget('key1', 'key2', 'key3');

// MSET
await redis.mset({ key1: 'value1', key2: 'value2' });

// INCR
await redis.incr('counter');

// INCRBY
await redis.incrby('counter', 5);

Hash Commands

// HSET
await redis.hset('user:1', { name: 'John', age: 30 });

// HGET
const name = await redis.hget('user:1', 'name');

// HGETALL
const user = await redis.hgetall('user:1');

// HMGET
const [name, age] = await redis.hmget('user:1', 'name', 'age');

List Commands

// LPUSH
await redis.lpush('list', 'item1', 'item2');

// RPUSH
await redis.rpush('list', 'item3');

// LRANGE
const items = await redis.lrange('list', 0, -1);

// LPOP
const item = await redis.lpop('list');

Set Commands

// SADD
await redis.sadd('set', 'member1', 'member2');

// SMEMBERS
const members = await redis.smembers('set');

// SISMEMBER
const isMember = await redis.sismember('set', 'member1');

Sorted Set Commands

// ZADD
await redis.zadd('leaderboard', { score: 100, member: 'player1' });

// ZRANGE
const topPlayers = await redis.zrange('leaderboard', 0, 9);

// ZRANK
const rank = await redis.zrank('leaderboard', 'player1');

JSON Commands

// JSON.SET
await redis.json.set('user:1', '$', { name: 'John', age: 30 });

// JSON.GET
const user = await redis.json.get('user:1', '$');

// JSON.NUMINCRBY
await redis.json.numincrby('user:1', '$.age', 1);

Key Management

// DEL
await redis.del('key');

// EXISTS
const exists = await redis.exists('key');

// EXPIRE
await redis.expire('key', 60);

// TTL
const ttl = await redis.ttl('key');

// KEYS (use with caution in production)
const keys = await redis.keys('user:*');

Complete Example

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

// Initialize client
const redis = new Redis({
  url: process.env.UPSTASH_REDIS_REST_URL!,
  token: process.env.UPSTASH_REDIS_REST_TOKEN!,
});

// Or use fromEnv
const redis = Redis.fromEnv();

// Simple operations
await redis.set('greeting', 'Hello, World!');
const greeting = await redis.get('greeting');

// Pipelining
const pipeline = redis.pipeline();
pipeline.set('user:1', { name: 'Alice' });
pipeline.set('user:2', { name: 'Bob' });
pipeline.get('user:1');
const results = await pipeline.exec();

// Transactions
const transaction = redis.multi();
transaction.set('balance', 100);
transaction.incrby('balance', 50);
transaction.get('balance');
const [setResult, incrResult, balance] = await transaction.exec();

// Scripts
const myScript = redis.createScript<number>(
  'return redis.call("INCR", KEYS[1])'
);
const counter = await myScript.exec(['mycounter'], []);

TypeScript Support

The Redis client is fully typed with TypeScript generics:
interface User {
  name: string;
  age: number;
}

// Type-safe operations
await redis.set<User>('user:1', { name: 'John', age: 30 });
const user = await redis.get<User>('user:1');
// user is typed as User | null

// JSON operations
await redis.json.set('user:2', '$', { name: 'Jane', age: 25 });
const userData = await redis.json.get<User>('user:2');

Build docs developers (and LLMs) love