ryan silva
ryan silva

Reputation: 31

how to connect to redis db with username and password nodejs node-redis

How can i connect to a Redis db that has username and password? below is the code example i'm trying to use, ( i'm using nodejs with node-redis and Redis version "redis": "^3.0.0",)

const client = redis.createClient({
  host: "localhost",
  port: 6379,
  password: "1234",
  username: "username"
});

Upvotes: 1

Views: 12371

Answers (2)

Arth Rathod
Arth Rathod

Reputation: 17

To connect Nodejs Project with Redis Version ^4.x:

const redisClient = redis.createClient({
  socket: {
    host: "localhost",
    port: 6379
  }
  password: "1234",
  username: "username"
});
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.connect();

If you don't Provide socket, password or username then by default it will connection on 127.0.0.1:6379

for by Default Connection use Beloved mention code

const redisClient = redis.createClient();
redisClient.on("error", (error) => console.error(`Error : ${error}`));
redisClient.connect();

Redis Installation in system https://redis.io/docs/getting-started/installation/install-redis-on-windows/

For More information About redis as node package https://www.npmjs.com/package/redis

and For mode Redis Command https://redis.io/commands/

Upvotes: 1

Guy Royse
Guy Royse

Reputation: 4312

Depends on the version of Node Redis that you are using. Since it looks like you are using Node Redis 3.x it would look like this:

const client = redis.createClient({
  host: "localhost",
  port: 6379,
  password: "1234",
  user: "username"
});

You could also connect using a connection string:

const client = redis.createClient("redis://username:1234@localhost:6379");

Full documentation for 3.x is available on the tagged branch in the GitHub repo for Node Redis.

That said, I would recommend using Node Redis 4.x as it supports Promises, newer Redis commands, and many common Redis modules like RedisJSON and RediSearch.

To connect using 4.x:

const client = redis.createClient({
  socket: {
    host: "localhost",
    port: 6379
  }
  password: "1234",
  username: "username"
});

or:

const client = redis.createClient({ url: "redis://username:1234@localhost:6379" });

Details on connecting using Node Redis 4.x can be found in the README on the main branch of Node Redis and in the Client Configuration Guide.

Upvotes: 3

Related Questions