Using Redis to Share ISR Cache in containerized self-hosted Next.js App
Tags: webdev, devops, nextjs, tutorial
Published: 2023-11-29 09:50:24

## Introduction

Welcome to this guide on integrating Redis, a reliable and exceptionally fast cache store, with Next.js. Why is configuring caching essential? As per Next.js's [official documentation](https://nextjs.org/docs/app/building-your-application/deploying#configuring-caching), default settings store cache in memory and on disk. However, in self-hosted containerized environments like Kubernetes, each pod has its copy of the cache, leading to potential stale data due to the lack of shared caching. By setting up Redis, you can ensure consistent, high-speed cache management across all pods, enhancing the scalability of your Next.js applications. Let's dive into how to achieve seamless integration.

## The tutorial

This tutorial will overview how to use Redis as the ISR/Data cache store for Next.js.

To share a cache, you must have several instances of your app running in the first place. It may be a container orchestration setup such as Kubernetes, Docker Swarm, Red Hat Open Shift, etc. The setup itself doesn't really matter.

Second, ensure that your app instances share the same [`buildId`](https://nextjs.org/docs/app/building-your-application/deploying#build-cache).

Third, configure your Redis how and where you want. The only requirement is to make it reachable for every app instance.

And you are almost good to go!

### Next.js configuration

Try the Next.js template with an already configured cache setup to test how things work. This template uses the [`@neshca/cache-handler`](https://github.com/caching-tools/next-shared-cache/tree/canary/packages/cache-handler) library to replace the default Next.js cache seamlessly. Start by creating a new Next.js application with a pre-configured Redis setup. This sets up a basic structure for your project with Redis integration. Run the following command to create the app:

```sh
npx create-next-app --example cache-handler-redis cache-handler-redis-app
```

Next, initialize the Redis client with your credentials. This involves creating a client instance with the Redis server's connection details. Replace the placeholders with your Redis server's `hostname`, `port`, `password`, and `database number`:

```js
const client = createClient({
  url: `redis://:${password}@${hostname}:${port}/${db_number}`,
});
```

**Note**: _If you want to use one Redis store for multiple apps, use the `db_number` or use [`buildId` as a key prefix](https://github.com/caching-tools/next-shared-cache/discussions/158) to separate the caches._

Use the following command to verify that your Redis cache is set up correctly and functioning. It lists all keys in your Redis database, allowing you to check if the caching is operational:

```sh
redis-cli KEYS *
```

Configure your `next.config.js` to use Redis for caching in production while disabling it in development mode. This ensures that your development environment runs smoothly without the need for Redis and enables the cache handler only when in production:

```js
const nextConfig = {
  experimental: {
    incrementalCacheHandlerPath:
      process.env.NODE_ENV === "production"
        ? require.resolve("./cache-handler-redis.js")
        : undefined, // disable cache handler in development
  },
};
```

If everything works fine, copy the `cache-handler-redis.js` file to your project near your `next.config.js`. Finally install the necessary dependencies for your caching setup. This includes the `@neshca/cache-handler` and Redis. Run the following command to add these to your project:

```sh
npm i -D @neshca/cache-handler redis
```

## Conclusion

You've successfully learned how to integrate Redis with Next.js, enhancing your application's scalability. For further information and advanced techniques, remember to check out the `@neshca/cache-handler` [documentation](https://caching-tools.github.io/next-shared-cache).