Published on

How To Implement Caching in Node.js Using Redis

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

Redis is a powerful NoSQL database commonly used for caching, session management, and real-time data processing. In this article, we will learn how to connect Redis with a Node.js application and implement a practical use case.


1. Prerequisites

  • Node.js and npm installed on your machine.
  • Redis running (can be local or remote).
  • Install the redis package for Node.js:
npm install redis

2. Basic Redis Connection Setup

Code Example:

const redis = require('redis')

// Create Redis client
const client = redis.createClient({
  host: '127.0.0.1', // Replace with your Redis host
  port: 6379, // Replace with your Redis port
})

// Handle connection events
client.on('connect', () => {
  console.log('Connected to Redis')
})

client.on('error', (err) => {
  console.error('Redis Error:', err)
})

// Connect to Redis
;(async () => {
  try {
    await client.connect()
    console.log('Successfully connected to Redis')
  } catch (error) {
    console.error('Redis connection failed:', error)
  }
})()

3. Performing Basic Operations

Set and Get Values

;(async () => {
  try {
    await client.set('key', 'value')
    const value = await client.get('key')
    console.log('Value:', value)
  } catch (error) {
    console.error('Redis operation error:', error)
  }
})()

Delete a Key

;(async () => {
  try {
    await client.del('key')
    console.log('Key deleted successfully')
  } catch (error) {
    console.error('Error deleting key:', error)
  }
})()

4. Real-World Use Case: Caching API Responses

Redis can be used to cache API data to reduce server load and improve response times.

Setup:

Install additional packages:

npm install express axios

Code Example:

const express = require('express')
const axios = require('axios')

const app = express()
const PORT = 3000

app.get('/data', async (req, res) => {
  const cacheKey = 'api:data'

  try {
    // Check cache
    const cachedData = await client.get(cacheKey)
    if (cachedData) {
      return res.json({ source: 'cache', data: JSON.parse(cachedData) })
    }

    // Fetch data from external API
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts')

    // Store in Redis cache with TTL (60 seconds)
    await client.setEx(cacheKey, 60, JSON.stringify(response.data))

    res.json({ source: 'API', data: response.data })
  } catch (error) {
    res.status(500).json({ error: 'Unable to fetch data' })
  }
})

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`)
})

5. Closing Redis Connection

Ensure you close the Redis connection when the application terminates:

process.on('SIGINT', async () => {
  await client.quit()
  console.log('Redis connection closed')
  process.exit(0)
})

Conclusion

Redis is a powerful tool that enhances the performance and flexibility of Node.js applications. By implementing basic operations and use cases like caching API responses, you can harness Redis to build faster and more efficient applications.