Skip to main content

How to cache JSON data in Redis with Node.js

Profile picture for Ajeet Raina
Ajeet Raina, Former Developer Growth Manager at Redis
Profile picture for Simon Prickett
Simon Prickett, Principal Developer Advocate at Redis

Node.js has become incredibly popular for both web and mobile application development. Node.js can be installed on MacOS, Linux and Windows systems. The Node Package Manager (npm) enables developers to install packages which are tried and tested libraries that help you to build applications quickly.

Node.js is a fast runtime, but adding the power, speed and flexibility of Redis can take it to the next level. Redis is best suited to situations that require data to be retrieved and delivered to the client as quickly as possible.

RedisJSON is an add-on module that adds JSON as a native data type to Redis. It enables atomic, in place operations to be performed on JSON documents stored in Redis.

We'll use the node-redis client to connect to Redis and leverage the power of RedisJSON.

Step 1. Run the Redis Stack Docker Container

This simple container image bundles together the latest stable releases of Redis and select Redis modules from Redis, Inc.

$ docker run -d -p 6379:6379 redis/redis-stack:latest

Step 2. Install Node.js

Download and install the current LTS (Long Term Support) version of Node.js from the website.

Step 3. Initialize an npm Project

Run npm init to initialize a new project. Use the default answers to all the questions:

$ mkdir jsondemo
$ cd jsondemo
$ npm init

Now edit package.json and add the line "type": "module". The file should look something like this:

"name": "jsondemo",
"type": "module",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "",
"license": "ISC"

Step 4. Install node-redis

node-redis is a high performance Node.js Redis client with support for the RedisJSON module. Install it using npm:

$ npm install redis

Step 5. Create a JavaScript File

Copy the code below into a file called app.js:

import { createClient } from 'redis';

async function redisJSONDemo() {
try {
const TEST_KEY = 'test_node';

const client = createClient();
await client.connect();

// RedisJSON uses JSON Path syntax. '.' is the root.
await client.json.set(TEST_KEY, '.', { node: 4303 });
const value = await client.json.get(TEST_KEY, {
// JSON Path: .node = the element called 'node' at root level.
path: '.node',

console.log(`value of node: ${value}`);

await client.quit();
} catch (e) {


Step 6. Run the Application

Start the application as follows:

$ node app.js

You should see this output:

value of node: 4303

Using the Redis MONITOR command, you can see the Redis commands that node-redis sent to the Redis server while running the application:

$ redis-cli> monitor

1637866932.281949 [0] "JSON.SET" "test_node" "." "{\"node\":4303}"
1637866932.282842 [0] "JSON.GET" "test_node" ".node"