Using Redis with Node.js


Originally published at:

Redis is a fast and efficient in-memory key-value store. It is also known as a data structure server, as the keys can contain strings, lists, sets, hashes and other data structures. If you are using Node.js, you can use the node_redis module to interact with Redis. This tutorial explains various ways of interacting with Redis from a Node.js app using the node_redis library.

Installing node_redis

node_redis, as you may have guessed, is the Redis client for Node.js. You can install it via npm using the following command.

npm install redis

Getting Started

Once you have installed node_redis module you are good to go. Let’s create a simple file, app.js, and see how to connect with Redis from Node.js.


var redis = require('redis');
var client = redis.createClient(); //creates a new client 

By default, redis.createClient() will use and 6379 as the hostname and port respectively. If you have a different host/port you can supply them as following:

var client = redis.createClient(port, host);

Now, you can perform some action once a connection has been established. Basically, you just need to listen for connect events as shown below.

client.on('connect', function() {

So, the following snippet goes into app.js:

var redis = require('redis');
var client = redis.createClient();

client.on('connect', function() {

Now, type node app in the terminal to run the app. Make sure your Redis server is up and running before running this snippet.

Storing Key-Value Pairs

Now that you know how to connect with Redis from Node.js, let’s see how to store key-value pairs in Redis storage.

Storing Strings

All the Redis commands are exposed as different functions on the client object. To store a simple string use the following syntax:

client.set('framework', 'AngularJS');


client.set(['framework', 'AngularJS']);

The above snippets store a simple string AngularJS against the key framework. You should note that both the snippets do the same thing. The only difference is that the first one passes a variable number of arguments while the later passes an args array to client.set() function. You can also pass an optional callback to get a notification when the operation is complete:

client.set('framework', 'AngularJS', function(err, reply) {

Continue reading this article on SitePoint



I have always been wanting to play with Redis. Thanks for this tutorial. Do you recommend a similar one for node mongo module?



Thanks for the comment! I would suggest mongoose for interacting with MongoDB from Node.



So u using this way for the webpages? Do you think that it's a really secure way - to make a web-accessible database?


closed #5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.