Using Redis for Scalable Server-Side Caching in Next.js

Integrate Redis as a server-side caching solution to store and retrieve data efficiently in a Next.js application.
import { createClient } from 'redis';

// Initialize Redis client
const redisClient = createClient({ url: 'redis://localhost:6379' });
redisClient.on('error', (err) => console.log('Redis Client Error', err));

export default redisClient;
This code initializes a Redis client using the 'redis' npm package. It connects to a Redis server running on localhost on port 6379 and exports the client for use in other parts of the Next.js application.
import redisClient from './redisClient';

export async function getCache(key) {
    await redisClient.connect();
    const data = await redisClient.get(key);
    await redisClient.quit();
    return data ? JSON.parse(data) : null;

export async function setCache(key, value, expiry = 3600) {
    await redisClient.connect();
    const result = await redisClient.setEx(key, expiry, JSON.stringify(value));
    await redisClient.quit();
    return result;
This code provides two utility functions for interacting with the Redis cache. getCache retrieves the value associated with a given key, parsing it as JSON. setCache saves a value associated with a key in the cache, with an optional expiry time, by default set to 3600 seconds (1 hour). Both functions ensure the Redis client connects before the operation and quits after completing the operation.
import { getCache, setCache } from './cache';

export default async function handler(req, res) {
    const cacheKey = 'myData';
    let data = await getCache(cacheKey);

    if (!data) {
        data = await fetchDataFromDatabase(); // Replace with actual data fetching logic
        await setCache(cacheKey, data);

This code shows an example of a Next.js API route handler that utilizes the caching functions. It tries to retrieve data from the cache using a specific cache key, and if it's not available, it fetches data from the database (or another source), caches it, and returns it in the response.