{
  "schema_version": 2,
  "id": "develop/clients/nodejs/connect",
  "title": "Connect to the server",
  "url": "https://redis.io/docs/latest/develop/clients/nodejs/connect/",
  "summary": "Connect your Node.js application to a Redis database",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-10-12T14:48:04+01:00",
  "page_type": "content",
  "content_hash": "472ba948b3f0f194090dea842b991a1ce09934a111614b46a5e3a2b938bc202d",
  "sections": [
    {
      "id": "basic-connection",
      "title": "Basic connection",
      "role": "overview",
      "text": "Connect to localhost on port 6379. \n\n[code example]\n\nStore and retrieve a simple string.\n\n[code example]\n\nStore and retrieve a map.\n\n[code example]\n\nTo connect to a different host or port, use a\n[connection URL](https://redis.io/docs/latest/develop/clients/connection-urls#node-redis-javascript):\n\n[code example]\n\n> [!NOTE]\n> A [connection URL](https://redis.io/docs/latest/develop/clients/connection-urls#node-redis-javascript) can\n> also set the host, port, credentials, database, and whether to use TLS,\n> so you can use one instead of passing those options separately.\n\nTo check if the client is connected and ready to send commands, use `client.isReady`, which returns a Boolean. `client.isOpen` is also available. This returns `true` when the client's underlying socket is open, and `false` when it isn't (for example, when the client is still connecting or reconnecting after a network error)."
    },
    {
      "id": "connect-to-a-redis-cluster",
      "title": "Connect to a Redis cluster",
      "role": "content",
      "text": "To connect to a Redis cluster, use `createCluster`.\n\n[code example]"
    },
    {
      "id": "connect-to-redis-sentinel",
      "title": "Connect to Redis Sentinel",
      "role": "content",
      "text": "To connect through [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel),\nuse `createSentinel()`. Set `name` to the name of the primary that the Sentinels monitor,\nand list one or more Sentinels in `sentinelRootNodes`. The client asks the Sentinels for\nthe current primary and switches to the new one after a failover.\n\n[code example]\n\nThe Sentinels and the data nodes have separate credentials. Set the Sentinel credentials in\n`sentinelClientOptions`, and the credentials for the primary and replicas in\n`nodeClientOptions`:\n\n[code example]\n\nNeither option accepts a `url`, so you can't use a connection string with\n`createSentinel()`.\n\nBy default, the client sends all commands to the primary. To send read-only commands such\nas `GET` to the replicas, set `replicaPoolSize` to the number of connections to open to each\nreplica. Replication is asynchronous, so a read that follows a write can return stale data.\n\n[code example]"
    },
    {
      "id": "connect-to-your-production-redis-with-tls",
      "title": "Connect to your production Redis with TLS",
      "role": "content",
      "text": "When you deploy your application, use TLS and follow the [Redis security](https://redis.io/docs/latest/operate/oss_and_stack/management/security) guidelines.\n\n[code example]\n\nYou can also use discrete parameters and UNIX sockets. Details can be found in the [client configuration guide](https://github.com/redis/node-redis/blob/master/docs/client-configuration.md)."
    },
    {
      "id": "connect-using-client-side-caching",
      "title": "Connect using client-side caching",
      "role": "content",
      "text": "Client-side caching is a technique to reduce network traffic between\nthe client and server, resulting in better performance. See\n[Client-side caching introduction](https://redis.io/docs/latest/develop/clients/client-side-caching)\nfor more information about how client-side caching works and how to use it effectively.\n\n> [!NOTE]\n> Client-side caching requires `node-redis` v5.1.0 or later.\n> To maximize compatibility with all Redis products, client-side caching\n> is supported by Redis v7.4 or later.\n>\n> The [Redis server products](https://redis.io/docs/latest/operate) support\n> [opt-in/opt-out](https://redis.io/docs/latest/develop/reference/client-side-caching#opt-in-and-opt-out-caching) mode\n> and [broadcasting mode](https://redis.io/docs/latest/develop/reference/client-side-caching#broadcasting-mode)\n> for CSC, but these modes are not currently implemented by `node-redis`.\n\nTo enable client-side caching, specify the\n[RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec#resp-versions)\nprotocol and configure the cache with the `clientSideCache` parameter\nwhen you connect. If you want `node-redis` to create the cache for you,\nthen you can pass a simple configuration object in `clientSideCache`, as\nshown below:\n\n[code example]\n\nHowever, you can get more control over the cache very easily by creating\nyour own cache object and passing that as `clientSideCache` instead:\n\n[code example]\n\nThe main advantage of using your own cache instance is that you can\nuse its methods to clear all entries, invalidate individual keys,\nand gather useful performance statistics:\n\n[code example]\n\nWhen you have connected, the usual Redis commands will work transparently\nwith the cache:\n\n[code example]\n\nYou can see the cache working if you connect to the same Redis database\nwith [`redis-cli`](https://redis.io/docs/latest/develop/tools/cli) and run the\n[`MONITOR`](https://redis.io/docs/latest/commands/monitor) command. If you run the\ncode above but without passing `clientSideCache` during the connection,\nyou should see the following in the CLI among the output from `MONITOR`:\n\n[code example]\n\nThe server responds to both `get(\"city\")` calls.\nIf you run the code with `clientSideCache` added in again, you will see\n\n[code example]\n\nThe first `get(\"city\")` call contacted the server, but the second\ncall was satisfied by the cache."
    },
    {
      "id": "pooled-caching",
      "title": "Pooled caching",
      "role": "content",
      "text": "You can also use client-side caching with client pools. Note that the same\ncache is shared among all the clients in the same pool. As with the\nnon-pooled connection, you can let `node-redis` create the cache for you:\n\n[code example]\n\nIf you want to access the cache, provide an instance of\n`BasicPooledClientSideCache` instead of `BasicClientSideCache`:\n\n[code example]"
    },
    {
      "id": "reconnect-after-disconnection",
      "title": "Reconnect after disconnection",
      "role": "content",
      "text": "`node-redis` can attempt to reconnect automatically when\nthe connection to the server is lost. By default, it will retry\nthe connection using an\n[exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff)\nstrategy with some random \"jitter\" added to avoid multiple\nclients retrying in sync with each other.\n\nYou can also set the\n`socket.reconnectionStrategy` field in the configuration to decide\nwhether to try to reconnect and how to approach it. Choose one of the following values for\n`socket.reconnectionStrategy`:\n\n-   `false`: Don't attempt to reconnect.\n-   `number`: Wait for this number of milliseconds and then attempt to reconnect.\n-   `<function>`: Use a custom\n    function to decide how to handle reconnection.\n\nThe custom function has the following signature:\n\n[code example]\n\nIt is called before each attempt to reconnect, with the `retries`\nindicating how many attempts have been made so far. The `cause` parameter is an\n[`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\nobject with information about how the connection was lost. The return value\nfrom the function can be any of the following:\n\n-   `false`: Don't attempt to reconnect.\n-   `number`: Wait this number of milliseconds and then try again.\n-   `Error`: Same as `false`, but lets you supply extra information about why\n    no attempt was made to reconnect.\n\nThe example below shows a `reconnectionStrategy` function that implements a\ncustom exponential backoff strategy:\n\n[code example]"
    },
    {
      "id": "connect-using-smart-client-handoffs-sch",
      "title": "Connect using Smart client handoffs (SCH)",
      "role": "content",
      "text": "*Smart client handoffs (SCH)* is a feature of Redis Cloud and\nRedis Software servers that lets them actively notify clients\nabout planned server maintenance shortly before it happens. This\nlets a client take action to avoid disruptions in service.\nSee [Smart client handoffs](https://redis.io/docs/latest/develop/clients/sch)\nfor more information about SCH.\n\n> [!NOTE]\n> Using SCH with node-redis requires v5.9.0 or later for\n> standard routing, and v5.11.0 or later for\n> [OSS Cluster API](https://redis.io/docs/latest/operate/rs/databases/configure/oss-cluster-api) connections.\n\nUse the configuration options shown in the example below to enable SCH\nduring the connection:\n\n[code example]\n\n> [!NOTE]\n> SCH requires the [RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec#resp-versions)\n> protocol, so you must set the `RESP:3` option explicitly when you connect.\n\nThe available options are:\n\n-   `maintNotifications`: (`string`) Whether or not to enable SCH. The options are  \n    -   `'disabled'`: don't use SCH\n    -   `'enabled'`: attempt to activate SCH on the server and abort the connection if it isn't supported\n    -   `'auto'`: attempt to activate SCH on the server and fall back to a non-SCH\n        connection if it isn't supported. This is the default.\n-   `maintEndpointType`: (`MovingEndpointType`) The type of endpoint to use for the connection. The options are:\n    -   `'external-ip'`: use the external IP address of the server\n    -   `'internal-ip'`: use the internal IP address of the server\n    -   `'external-fqdn'`: use the external FQDN of the server\n    -   `'internal-fqdn'`: use the internal FQDN of the server\n    -   `'auto'`: auto-detect based on connection. This is the default.\n    -   `'none'`: attempt a graceful reconnect to the current endpoint after a delay.\n-   `maintRelaxedCommandTimeout`: (`number`) The command timeout to use while the server is \n    performing maintenance. The default is 10000 (10 seconds). If a timeout happens during the maintenance period, the client receives a `CommandTimeoutDuringMaintenance` error.\n-   `maintRelaxedSocketTimeout`: (`number`) The socket timeout to use while the server is \n    performing maintenance. The default is 10000 (10 seconds). If a timeout happens during the maintenance period, the client receives a `SocketTimeoutDuringMaintenance` error.\n\n> [!NOTE]\n>  Redis Cloud supports relaxed timeouts *only* (and not pre-handoffs) for SCH if you are using\n> either [AWS PrivateLink](https://redis.io/docs/latest/operate/rc/security/aws-privatelink) or\n> [Google Cloud Private Service Connect](https://redis.io/docs/latest/operate/rc/security/private-service-connect)\n> (see [Smart client handoffs](https://redis.io/docs/latest/develop/clients/sch#redis-cloud) for more information).\n> To use relaxed timeouts with these services, you should set `maintEndpointType: 'none'`\n> when you connect. All other configurations have full support for both relaxed timeouts and pre-handoffs."
    },
    {
      "id": "connection-events",
      "title": "Connection events",
      "role": "content",
      "text": "The client object emits the following\n[events](https://developer.mozilla.org/en-US/docs/Web/API/Event) that are\nrelated to connection:\n\n-   `connect`: (No parameters) The client is about to start connecting to the server.\n-   `ready`: (No parameters) The client has connected and is ready to use.\n-   `end`: (No parameters) The client has been intentionally closed using `client.quit()`.\n-   `error`: An error has occurred, which is described by the\n    [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n    parameter. This is usually a network issue such as \"Socket closed unexpectedly\".\n-   `reconnecting`: (No parameters) The client is about to try reconnecting after the\n    connection was lost due to an error.\n-   `sharded-channel-moved`: The cluster slot of a subscribed\n    [sharded pub/sub channel](https://redis.io/docs/latest/develop/pubsub#sharded-pubsub)\n    has been moved to another shard. Note that when you use a\n    [`RedisCluster`](#connect-to-a-redis-cluster) connection, this event is automatically\n    handled for you. See\n    [`sharded-channel-moved` event](https://github.com/redis/node-redis/blob/master/docs/pub-sub.md#sharded-channel-moved-event) for more information.\n\nUse code like the following to respond to these events:\n\n[code example]"
    }
  ],
  "examples": [
    {
      "id": "basic-connection-ex0",
      "language": "js",
      "code": "import { createClient } from 'redis';\n\nconst client = createClient();\n\nclient.on('error', err => console.log('Redis Client Error', err));\n\nawait client.connect();",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex1",
      "language": "js",
      "code": "await client.set('key', 'value');\nconst value = await client.get('key');",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex2",
      "language": "js",
      "code": "await client.hSet('user-session:123', {\n    name: 'John',\n    surname: 'Smith',\n    company: 'Redis',\n    age: 29\n})\n\nlet userSession = await client.hGetAll('user-session:123');\nconsole.log(JSON.stringify(userSession, null, 2));\n/*\n{\n  \"surname\": \"Smith\",\n  \"name\": \"John\",\n  \"company\": \"Redis\",\n  \"age\": \"29\"\n}\n */",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex3",
      "language": "js",
      "code": "createClient({\n  url: 'redis://alice:foobared@awesome.redis.server:6380'\n});",
      "section_id": "basic-connection"
    },
    {
      "id": "connect-to-a-redis-cluster-ex0",
      "language": "js",
      "code": "import { createCluster } from 'redis';\n\nconst cluster = createCluster({\n    rootNodes: [\n        {\n            url: 'redis://127.0.0.1:16379'\n        },\n        {\n            url: 'redis://127.0.0.1:16380'\n        },\n        // ...\n    ]\n});\n\ncluster.on('error', (err) => console.log('Redis Cluster Error', err));\n\nawait cluster.connect();\n\nawait cluster.set('foo', 'bar');\nconst value = await cluster.get('foo');\nconsole.log(value); // returns 'bar'\n\nawait cluster.close();",
      "section_id": "connect-to-a-redis-cluster"
    },
    {
      "id": "connect-to-redis-sentinel-ex0",
      "language": "js",
      "code": "import { createSentinel } from 'redis';\n\nconst sentinel = createSentinel({\n    name: 'mymaster',\n    sentinelRootNodes: [\n        { host: 'localhost', port: 26379 },\n        { host: 'localhost', port: 26380 },\n        { host: 'localhost', port: 26381 }\n    ]\n});\n\nsentinel.on('error', (err) => console.log('Redis Sentinel Error', err));\n\nawait sentinel.connect();\n\nawait sentinel.set('foo', 'bar');\nconst value = await sentinel.get('foo');\nconsole.log(value); // returns 'bar'\n\nawait sentinel.close();",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-redis-sentinel-ex1",
      "language": "js",
      "code": "const sentinel = createSentinel({\n    name: 'mymaster',\n    sentinelRootNodes: [\n        { host: 'localhost', port: 26379 },\n        { host: 'localhost', port: 26380 },\n        { host: 'localhost', port: 26381 }\n    ],\n    // Credentials for the Sentinel instances.\n    sentinelClientOptions: {\n        password: 'sentinel-secret'\n    },\n    // Credentials for the primary and replica data nodes.\n    nodeClientOptions: {\n        username: 'default',\n        password: 'secret'\n    }\n});",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-redis-sentinel-ex2",
      "language": "js",
      "code": "const sentinel = createSentinel({\n    name: 'mymaster',\n    sentinelRootNodes: [\n        { host: 'localhost', port: 26379 }\n    ],\n    replicaPoolSize: 1\n});",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-your-production-redis-with-tls-ex0",
      "language": "js",
      "code": "const client = createClient({\n    username: 'default', // use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/\n    password: 'secret', // use your password here\n    socket: {\n        host: 'my-redis.cloud.redislabs.com',\n        port: 6379,\n        tls: true,\n        key: readFileSync('./redis_user_private.key'),\n        cert: readFileSync('./redis_user.crt'),\n        ca: [readFileSync('./redis_ca.pem')]\n    }\n});\n\nclient.on('error', (err) => console.log('Redis Client Error', err));\n\nawait client.connect();\n\nawait client.set('foo', 'bar');\nconst value = await client.get('foo');\nconsole.log(value) // returns 'bar'\n\nawait client.destroy();",
      "section_id": "connect-to-your-production-redis-with-tls"
    },
    {
      "id": "connect-using-client-side-caching-ex0",
      "language": "js",
      "code": "const client = createClient({\n  RESP: 3,\n  clientSideCache: {\n    ttl: 0,             // Time-to-live in milliseconds (0 = no expiration)\n    maxEntries: 0,      // Maximum entries to store (0 = unlimited)\n    evictPolicy: \"LRU\"  // Eviction policy: \"LRU\" or \"FIFO\"\n  }\n});",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex1",
      "language": "js",
      "code": "import { BasicClientSideCache } from 'redis';\n\nconst cache = new BasicClientSideCache({\n  ttl: 0,\n  maxEntries: 0,\n  evictPolicy: \"LRU\"\n});\n\nconst client = createClient({\n  RESP: 3,\n  clientSideCache: cache\n});",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex2",
      "language": "js",
      "code": "// Manually invalidate keys\ncache.invalidate(key);\n\n// Clear the entire cache\ncache.clear();\n\n// Get cache metrics\n// `cache.stats()` returns a `CacheStats` object with comprehensive statistics.\nconst statistics = cache.stats();\n\n// Key metrics:\nconst hits = statistics.hitCount;        // Number of cache hits\nconst misses = statistics.missCount;      // Number of cache misses\nconst hitRate = statistics.hitRate();     // Cache hit rate (0.0 to 1.0)\n\n// Many other metrics are available on the `statistics` object, e.g.:\n// statistics.missRate(), statistics.loadSuccessCount,\n// statistics.averageLoadPenalty(), statistics.requestCount()",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex3",
      "language": "java",
      "code": "client.set(\"city\", \"New York\");\nclient.get(\"city\");     // Retrieved from Redis server and cached\nclient.get(\"city\");     // Retrieved from cache",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex4",
      "language": "plaintext",
      "code": "1723109720.268903 [...] \"SET\" \"city\" \"New York\"\n1723109720.269681 [...] \"GET\" \"city\"\n1723109720.270205 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex5",
      "language": "plaintext",
      "code": "1723110248.712663 [...] \"SET\" \"city\" \"New York\"\n1723110248.713607 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "pooled-caching-ex0",
      "language": "js",
      "code": "const client = createClientPool({RESP: 3}, {\n  clientSideCache: {\n    ttl: 0,\n    maxEntries: 0,\n    evictPolicy: \"LRU\"\n  },\n  minimum: 5\n});",
      "section_id": "pooled-caching"
    },
    {
      "id": "pooled-caching-ex1",
      "language": "js",
      "code": "import { BasicPooledClientSideCache } from 'redis';\n\nconst cache = new BasicPooledClientSideCache({\n  ttl: 0,\n  maxEntries: 0,\n  evictPolicy: \"LRU\"\n});\n\nconst client = createClientPool({RESP: 3}, {\n  clientSideCache: cache,\n  minimum: 5\n});",
      "section_id": "pooled-caching"
    },
    {
      "id": "reconnect-after-disconnection-ex0",
      "language": "js",
      "code": "(retries: number, cause: Error) => false | number | Error",
      "section_id": "reconnect-after-disconnection"
    },
    {
      "id": "reconnect-after-disconnection-ex1",
      "language": "js",
      "code": "createClient({\n  socket: {\n    reconnectStrategy: retries => {\n        // Generate a random jitter between 0 – 100 ms:\n        const jitter = Math.floor(Math.random() * 100);\n\n        // Delay is an exponential backoff, (2^retries) * 50 ms, with a\n        // maximum value of 3000 ms:\n        const delay = Math.min(Math.pow(2, retries) * 50, 3000);\n\n        return delay + jitter;\n    }\n  }\n});",
      "section_id": "reconnect-after-disconnection"
    },
    {
      "id": "connect-using-smart-client-handoffs-sch-ex0",
      "language": "js",
      "code": "const client = createClient({\n  RESP: 3,\n  maintNotifications: 'auto',\n  maintEndpointType: 'auto',\n  maintRelaxedCommandTimeout: 10000,\n  maintRelaxedSocketTimeout: 10000,\n  ...\n});",
      "section_id": "connect-using-smart-client-handoffs-sch"
    },
    {
      "id": "connection-events-ex0",
      "language": "js",
      "code": "client.on('error', error => {\n    console.error(`Redis client error:`, error);\n});",
      "section_id": "connection-events"
    }
  ]
}
