出品者:jax

A modern, high-performance Redis client for Node.js with full support for Redis Stack modules including Search, JSON, Bloom filters, Time Series, and Entra ID authentication.
@redis/client)This block provides the core Redis client implementation for Node.js, including standalone client, cluster client, pub/sub, pipelining, multi/exec transactions, client-side caching, and OpenTelemetry observability. It targets backend engineers building Node.js or TypeScript services that need a production-grade Redis connection layer without pulling in the full redis meta-package.
RESP/ - RESP2/RESP3 protocol types and codec (type definitions for all reply shapes)authx/ - Token-based and streaming credentials providers, token manager, identity provider abstractionsclient/ - Core RedisClient implementation: socket, commands queue, pub/sub, pool, parser, cache, tracingcluster/ - RedisCluster client with slot routing, cluster topology managementcommands/ - Individual Redis command implementations (ACL, APPEND, BITCOUNT, CLIENT_, CLUSTER_, and hundreds more)opentelemetry/ - OpenTelemetry singleton for metrics instrumentation (connection, pub/sub, resiliency)sentinel/ - Redis Sentinel support for high-availability standalone deploymentsutils/ - Shared internal utilitiescommander.ts - Generic command attachment and argument prefix helperserrors.ts - Typed error classes (ClientClosedError, ClientOfflineError, WatchError, etc.)lua-script.ts - Lua script definition helpersmulti-command.ts - Multi/exec pipeline base logicsingle-entry-cache.ts - Single-slot LRU cache utilitytest-utils.ts - Test helpers (not for production use)npm install redis
# or, for only the core client without stack modules:
npm install @redis/client
If you want OpenTelemetry metrics:
npm install @opentelemetry/api @opentelemetry/sdk-metrics
No native modules, no pod install, no Android linking required. Pure JavaScript/TypeScript.
Copy the source/ directory into your project, e.g. .
隔離されたサンドボックスを起動しサーバー側で実行 — ローカル設定不要。
このバージョンの Tetrees AI Review
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
パイプライン avcp-2026-08-04.1 · SHA-256 100dd35325cff1a9…
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.
レビュー日 2026年8月4日
この製品をお使いのAI IDE・Webビルダー・クラウドIDEに直接取り込みます。
Tetreesを対応AI IDEに接続し、所有製品の一覧取得と検証済みZIPの取得を、販売者のアップロード権限を公開せずに行えます。
まだレビューがありません。
Sign in to join the discussion
Loading discussion…
src/redis-client/source/Add path aliases to tsconfig.json if importing directly from source (otherwise skip - use the npm package):
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@redis/client": ["src/redis-client/source"],
"@redis/client/*": ["src/redis-client/source/*"]
},
"moduleResolution": "node16",
"target": "ES2020",
"lib": ["ES2020"],
"strict": true
}
}
Ensure "esModuleInterop": true is set - the source uses mixed default/named exports.
Set environment variables as needed:
REDIS_URL=redis://localhost:6379
# For TLS:
REDIS_URL=rediss://user:pass@host:6380
.connect() resolves.RedisClientOptionsimport { createClient } from '@redis/client';
interface RedisClientOptions<M, F, S, RESP, TYPE_MAPPING, SocketOptions> {
url?: string; // redis[s]://[[user][:pass]@][host][:port][/db]
socket?: RedisSocketOptions; // TCP/TLS/Unix socket config
username?: string;
password?: string;
credentialsProvider?: CredentialsProvider | StreamingCredentialsProvider;
// ... modules, functions, scripts, resp version, type mapping
}
Use RedisClientOptions when constructing a client via createClient(). Supply url for simple setups; use socket for TLS, Unix sockets, or keep-alive tuning. If both credentialsProvider and username/password are set, credentialsProvider wins.
OpenTelemetry.initimport { OpenTelemetry } from '@redis/client'; // re-exported from opentelemetry/index.ts
OpenTelemetry.init(config: ObservabilityConfig): void
Singleton initializer for node-redis metrics. Call once at application startup before creating any Redis clients you want to observe. Throws OpenTelemetryError if called twice or if @opentelemetry/api is not installed. Supports metric groups: "pubsub", "connection-basic", "resiliency".
TokenManager / StreamingCredentialsProviderimport {
TokenManager,
TokenManagerConfig,
StreamingCredentialsProvider,
StreamingCredentialsListener,
RetryPolicy
} from '@redis/client'; // re-exported from authx/index.ts
TokenManager wraps an IdentityProvider and continuously refreshes tokens, emitting updates to registered TokenStreamListeners. Use StreamingCredentialsProvider to supply dynamically-rotating credentials (e.g. Entra ID tokens) to a RedisClient without reconnecting. Set a RetryPolicy to control back-off on token fetch failures.
RedisClusterOptionsimport { createCluster } from '@redis/client';
interface RedisClusterOptions<M, F, S, RESP, TYPE_MAPPING> {
rootNodes: Array<RedisClusterClientOptions>; // at least 3 nodes recommended
defaults?: Partial<RedisClusterClientOptions>;
// modules, functions, scripts, resp, typeMapping
}
Used with createCluster(). rootNodes seeds topology discovery; defaults applies global settings (TLS, credentials, timeouts) to every shard client. The cluster client handles slot routing, ASKING redirects, and re-subscription automatically.
A minimal Express service connecting to Redis, setting and getting a key, then cleanly disconnecting on shutdown.
import { createClient } from '@redis/client';
const client = createClient({
url: process.env.REDIS_URL ?? 'redis://localhost:6379',
socket: {
reconnectStrategy: (retries) => Math.min(retries * 50, 2000),
connectTimeout: 5000,
},
});
client.on('error', (err) => console.error('Redis error:', err));
client.on('reconnecting', () => console.log('Redis reconnecting...'));
await client.connect();
await client.set('session:abc', JSON.stringify({ userId: 42 }), { EX: 3600 });
const raw = await client.get('session:abc');
const session = raw ? JSON.parse(raw) : null;
console.log(session); // { userId: 42 }
process.on('SIGTERM', async () => {
await client.quit();
process.exit(0);
});
Connect to a Redis Cluster, perform an atomic counter increment inside a MULTI/EXEC block.
import { createCluster } from '@redis/client';
const cluster = createCluster({
rootNodes: [
{ socket: { host: '10.0.0.1', port: 6379 } },
{ socket: { host: '10.0.0.2', port: 6379 } },
{ socket: { host: '10.0.0.3', port: 6379 } },
],
defaults: {
socket: { tls: false },
},
});
cluster.on('error', (err) => console.error('Cluster error:', err));
await cluster.connect();
// MULTI/EXEC on a single key (same slot)
const results = await cluster.multi()
.incr('counter:visits')
.expire('counter:visits', 86400)
.exec();
console.log('INCR result:', results[0]); // e.g. 1
console.log('EXPIRE result:', results[1]); // 1
await cluster.disconnect();
Bootstrap metrics before creating clients so that connection and command latency are tracked.
import { metrics } from '@opentelemetry/api';
import {
MeterProvider,
PeriodicExportingMetricReader,
ConsoleMetricExporter,
} from '@opentelemetry/sdk-metrics';
import { OpenTelemetry, createClient } from '@redis/client';
// 1. Set up OTel SDK
const provider = new MeterProvider({
readers: [
new PeriodicExportingMetricReader({
exporter: new ConsoleMetricExporter(),
exportIntervalMillis: 10_000,
}),
],
});
metrics.setGlobalMeterProvider(provider);
// 2. Init node-redis OTel - must happen before createClient
OpenTelemetry.init({
metrics: {
enabled: true,
enabledMetricGroups: ['connection-basic', 'resiliency'],
},
});
// 3. Create and use client normally
const client = createClient({ url: 'redis://localhost:6379' });
client.on('error', console.error);
await client.connect();
await client.ping();
await client.quit();
Use StreamingCredentialsProvider (from authx/) to rotate credentials dynamically without reconnecting.
import { createClient, StreamingCredentialsProvider, StreamingCredentialsListener } from '@redis/client';
// Minimal custom streaming provider
class MyCredentialsProvider implements StreamingCredentialsProvider {
subscribe(listener: StreamingCredentialsListener): { dispose: () => void } {
// Push initial credentials
listener.onNext({ username: 'myuser', password: 'initialpass' });
const interval = setInterval(() => {
// Rotate credentials from your identity provider
listener.onNext({ username: 'myuser', password: fetchNewToken() });
}, 55_000);
return { dispose: () => clearInterval(interval) };
}
}
function fetchNewToken(): string {
return 'rotated-token-' + Date.now();
}
const client = createClient({
url: 'redis://localhost:6379',
credentialsProvider: new MyCredentialsProvider(),
});
client.on('error', console.error);
await client.connect();
await client.set('secure-key', 'value');
await client.quit();
RESP/ - Protocol-level type definitions: Command, CommandArguments, TypeMapping, RespVersions, reply types. The foundation every other module builds on.authx/ - Credentials and token lifecycle: CredentialsProvider, StreamingCredentialsProvider, TokenManager, IdentityProvider, Token, Disposable. Used by the client for re-authentication without reconnect.client/ - The RedisClient class and all its internals: socket management (socket.ts), command queue with back-pressure (commands-queue.ts), pub/sub channel management (pub-sub.ts), client-side caching (cache.ts), connection pool (pool.ts), legacy callback mode (legacy-mode.ts), OTel tracing hooks (tracing.ts).cluster/ - RedisCluster client: slot map (cluster-slots.ts), multi-command for cluster (multi-command.ts), cluster index with createCluster.commands/ - One file per Redis command. Each exports a typed transformArguments and transformReply pair consumed by commander.ts.opentelemetry/ - OpenTelemetry singleton, ClientRegistry, metrics definitions. Optional; only activates when initialized.sentinel/ - Sentinel-based HA client for automatic primary discovery and failover.utils/ - Internal helpers shared across modules.commander.ts - Attaches command definitions to client instances; handles argument prefixes for scripts and functions.errors.ts - Typed error hierarchy: ClientClosedError, ClientOfflineError, WatchError, DisconnectsClientError, ErrorReply.lua-script.ts - Defines Lua scripts as first-class Redis script objects with SHA caching.multi-command.ts - Base MULTI/EXEC queue logic shared by standalone and cluster multi-command classes.single-entry-cache.ts - Tiny single-slot cache used internally for repeated argument parsing results.test-utils.ts - Test infrastructure helpers; do not import in production code.connect() resolves: all commands queue and will reject with ClientOfflineError if the client is never connected; always await client.connect() before issuing commands.OpenTelemetry.init called more than once: it is a strict singleton and throws OpenTelemetryError on a second call; guard with a module-level flag or call only in your app entry point.credentialsProvider ignored when username/password also set: credentialsProvider takes precedence - remove username/password from options when using a provider.{tag} in key names to force co-location.import/export; if your project is CommonJS set "esModuleInterop": true and "allowSyntheticDefaultImports": true in tsconfig.json.@opentelemetry/api peer dep missing at runtime: the OTel module does a dynamic require; if the package is absent it throws OpenTelemetryError - install @opentelemetry/api before calling OpenTelemetry.init.I have dropped the node-redis core client source into `src/redis-client/source/`
and have a USAGE.md at `src/redis-client/USAGE.md`.
The upstream package is `@redis/client` (part of the `node-redis` monorepo).
Please help me integrate this into my existing Node.js/TypeScript project step by step:
1. Read USAGE.md and the file excerpts for `client/index.ts`, `cluster/index.ts`,
`authx/index.ts`, and `opentelemetry/index.ts` to understand the exported API.
2. Add the necessary `npm install` commands for runtime dependencies.
3. Wire up a `RedisClient` singleton (using `createClient`) with proper error handling
and graceful shutdown in my Express app entry point (`src/app.ts`).
4. If I need cluster support, create a `RedisCluster` using `createCluster` with my
node list from environment variables.
5. If I need OpenTelemetry, call `OpenTelemetry.init` before any client is created.
6. Show me how to wrap common operations (GET/SET with TTL, MULTI/EXEC, pub/sub
subscribe) using the real exports from `source/client/index.ts`.
7. Point out any TypeScript config changes needed (`tsconfig.json` paths, module
resolution) for this source to compile correctly alongside my existing code.
Use only the real exported symbols documented in USAGE.md. Do not invent APIs.
node-redis is released under the MIT License. See source/LICENSE if present, or refer to the upstream repository. Credit: the Redis open-source community and contributors at https://github.com/redis/node-redis.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完全なインストールガイドと統合プロンプトは購入後に解放されます。
Automation, Utilities & Developer Tools
無料