---
title: Creating a Session Store with Redis and Next.js
description: Learn how to durably store sessions with Redis and Next.js.
url: /kb/guide/session-store-nextjs-redis-vercel-kv
canonical_url: "https://vercel.com/kb/guide/session-store-nextjs-redis-vercel-kv"
published: 2025-11-03
last_updated: 2025-11-10
authors: Lee Robinson
related:
  - /docs/redis
install_vercel_plugin: npx plugins add vercel/vercel-plugin
---
<!-- docsgraph:related -->
## Related pages

> **For AI agents:** Follow these links to understand how this page connects to the rest of the Vercel ecosystem. For the full cross-link map (inbound, outbound, prerequisites, and semantic neighbors), see the .graph.md link below.

- [Authentication with Cache Components](https://nextjs.org/docs/app/guides/authentication-with-cache-components?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to read the user session, show authenticated UI without slowing down the page, and cache data derived from the
- [Authentication](https://nextjs.org/docs/pages/guides/authentication?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to implement authentication in Next.js, covering best practices, securing routes, authorization techniques, an
- [Authentication](https://nextjs.org/docs/app/guides/authentication?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to implement authentication in your Next.js application.
- [Data Cache](https://vercel.com/docs/caching/runtime-cache/data-cache?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Vercel Data Cache is a specialized cache that stores responses from data fetches in Next.js App Router
- [Mutating Data](https://nextjs.org/docs/app/getting-started/mutating-data?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to mutate data using Server Functions and Server Actions in Next.js.
- [Self-Hosting](https://nextjs.org/docs/pages/guides/self-hosting?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to self-host your Next.js application on a Node.js server, Docker image, or static HTML files (static exports)
- [Getting Started](https://vercel.com/docs/global-config/get-started?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=related) — Learn how to create a Global Config store and read from it in your project.

Full cross-link map for this page: [/kb/guide/session-store-nextjs-redis-vercel-kv.graph.md](/kb/guide/session-store-nextjs-redis-vercel-kv.graph.md?from=related&source_path=%2Fkb%2Fguide%2Fsession-store-nextjs-redis-vercel-kv&source_site=vercel-kb&relationship=graph)
<!-- /docsgraph:related -->


In this guide, we will learn how to durably store sessions with [Redis on Vercel](https://vercel.com/docs/redis) and [Next.js](https://nextjs.org).

## What are sessions?

Sessions are used to persist user data across multiple requests. When a user visits your application, a session is initiated and used to store data related to that particular user. This is useful for maintaining user-specific states and persisting data across the lifecycle of a user's interaction with the application.

For instance, consider a shopping site. Once a user adds an item to their cart, this data can be stored in a session. This allows the user to navigate to different parts of the site, and when they return to their cart, the items are still there. This is made possible by the persistent nature of sessions.

## Storing sessions with Redis

You can store and manage sessions with Redis. Here is a step-by-step explanation of how to build your own session store.

### 1\. Importing Required Libraries

We start off by importing the necessary modules. We install and import `server-only` to ensure the server-side code [can't be exposed to the client](https://nextjs.org/docs/getting-started/react-essentials#keeping-server-only-code-out-of-client-components-poisoning). We import `cookies` from `next/headers` to handle the session id cookie, and finally Redis:

```javascript
import "server-only";
import { cookies } from "next/headers";
import Redis from "ioredis";

// Create a new Redis instance
const redis = new Redis(process.env.REDIS_URL);
```

### 2\. Handling Session IDs

These functions handle the creation and retrieval of a session id which is unique for each session. This id is used to differentiate between different users or sessions. If a session id does not exist, a new one is created and set into the cookies.

```tsx
type SessionId = string;

export async function getSessionId(): SessionId | undefined {
  const cookieStore = await cookies();
  return cookieStore.get("session-id")?.value;
}

function await setSessionId(sessionId: SessionId): void {
  const cookieStore = await cookies();
  cookieStore.set("session-id", sessionId);
}

export async function getSessionIdAndCreateIfMissing() {
  const sessionId = await getSessionId();
  if (!sessionId) {
    const newSessionId = crypto.randomUUID();
    await setSessionId(newSessionId);

    return newSessionId;
  }

  return sessionId;
}
```

### 3\. Handling Session Data

These functions provide an interface to the Redis store for the session. `get` is used to retrieve a value for a specific key, `getAll` is used to retrieve all key-value pairs for a session, and `set` is used to set a value for a specific key.

```tsx
export async function get(key: string, namespace: string = "") {
  const sessionId = await getSessionId();
  if (!sessionId) {
    return null;
  }
  return redis.hget(`session-${namespace}-${sessionId}`, key);
}

export async function getAll(namespace: string = "") {
  const sessionId = await getSessionId();
  if (!sessionId) {
    return null;
  }
  return redis.hgetall(`session-${namespace}-${sessionId}`);
}

export async function set(key: string, value: string, namespace: string = "") {
  const sessionId = await getSessionIdAndCreateIfMissing();
  return redis.hset(`session-${namespace}-${sessionId}`, key, value);
}
```

Remember that the `'key'` here represents a particular piece of data you want to store, like `'username'` or `'cart-items'`. The `'namespace'` is an optional argument that you can use to further segregate your data.

## Usage of sessions with Next.js

To use this code in your Next.js application, import the functions provided in this module wherever you need to set or get session data. For example:

```javascript
import { get, set } from './session-store';

// Storing a user's name in the session
await set('username', 'John Doe');

// Getting the user's name from the session
const username = await get('username');

console.log(username); // Outputs: 'John Doe'
```

This example sets the username `'John Doe'` to the session and retrieves it later. It demonstrates a basic usage of the session store we just created. You can store and retrieve any kind of data as required by your application.

`get()` can be called from [React Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components), [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations), and [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers). `set()` can be called from [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations) or [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers). We recommend using Server Actions.