Connect to the server
Connect your Node.js application to a Redis database
Basic connection
Connect to localhost on port 6379.
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
Store and retrieve a simple string.
await client.set('key', 'value');
const value = await client.get('key');
Store and retrieve a map.
await client.hSet('user-session:123', {
name: 'John',
surname: 'Smith',
company: 'Redis',
age: 29
})
let userSession = await client.hGetAll('user-session:123');
console.log(JSON.stringify(userSession, null, 2));
/*
{
"surname": "Smith",
"name": "John",
"company": "Redis",
"age": "29"
}
*/
To connect to a different host or port, use a connection string in the format redis[s]://[[username][:password]@][host][:port][/db-number]
:
createClient({
url: 'redis://alice:foobared@awesome.redis.server:6380'
});
To 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).
Connect to a Redis cluster
To connect to a Redis cluster, use createCluster
.
import { createCluster } from 'redis';
const cluster = createCluster({
rootNodes: [
{
url: 'redis://127.0.0.1:16379'
},
{
url: 'redis://127.0.0.1:16380'
},
// ...
]
});
cluster.on('error', (err) => console.log('Redis Cluster Error', err));
await cluster.connect();
await cluster.set('foo', 'bar');
const value = await cluster.get('foo');
console.log(value); // returns 'bar'
await cluster.quit();
Connect to your production Redis with TLS
When you deploy your application, use TLS and follow the Redis security guidelines.
const client = createClient({
username: 'default', // use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/
password: 'secret', // use your password here
socket: {
host: 'my-redis.cloud.redislabs.com',
port: 6379,
tls: true,
key: readFileSync('./redis_user_private.key'),
cert: readFileSync('./redis_user.crt'),
ca: [readFileSync('./redis_ca.pem')]
}
});
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
await client.set('foo', 'bar');
const value = await client.get('foo');
console.log(value) // returns 'bar'
await client.disconnect();
You can also use discrete parameters and UNIX sockets. Details can be found in the client configuration guide.