In order to use Redis with Node.js, you need to install a Node.js Redis client. The following sections demonstrate the use of ioredis, a community-recommended Redis client for Node.js with build-in support for promises.
Another community-recommended client for Node.js developers is node_redis. Additional Node.js clients for Redis can be found under the Node.js section of the Redis Clients page.
This example code creates a connection to Redis:
const Redis = require('ioredis');
const redis = new Redis({
host: '<hostname>',
port: <port>,
password: '<password>'
});
Replace the values in the example with the values for your Redis instance:
- The name of the host your database runs on - The port that the database is running on (default: 6379) - The default Redis password, if configured Note: Remember to always store passwords outside of your code, for example in environment variables.
This example shows how to configure ioredis to make a connection to Redis using TLS:
const Redis = require('ioredis');
const fs = require('fs');
const redis = new Redis({
host: 'hostname',
port: <port>,
tls: {
key: fs.readFileSync('path_to_keyfile', 'ascii'),
cert: fs.readFileSync('path_to_certfile', 'ascii'),
ca: [ fs.readFileSync('path_to_ca_certfile', 'ascii') ]
}
});
Where you must provide:
- The name of the host your database runs on - The port that the database is running on (default: 6379)