Next.js App Router Cookie Management

2.1.1 · active · verified Wed Apr 22

This library provides comprehensive cookie management for Next.js 13+ applications, specifically designed for the App Router. It offers solutions for both client-side components (SSR-capable) and server-only components. The current stable version is 2.1.1. While a specific release cadence isn't stated, the package appears actively maintained, indicated by recent updates and explicit migration instructions from v1. Key differentiators include its ability to support client components rendered on the server (SSR) with a special dehydration mechanism for cookie updates, a capability not natively offered by Next.js for server components. Its client-side interface is based on the popular `js-cookie` package, providing a familiar API. It addresses the challenge of handling cookies consistently across the varied rendering environments of Next.js's App Directory.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates setting up CookiesProvider in `app/layout.tsx` and using the `useCookies` hook in a client component to read, set, and delete cookies.

'use client';

import { useCookies } from 'next-client-cookies';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <CookiesProvider>{children}</CookiesProvider>
      </body>
    </html>
  );
}

// In a client component (e.g., app/my-component.tsx)
// Make sure your component file starts with 'use client';
const MyCookieComponent = () => {
  const cookies = useCookies();

  return (
    <div>
      <p>My cookie value: {cookies.get('my-cookie') ?? 'Not set'}</p>

      <button onClick={() => cookies.set('my-cookie', 'my-value', { expires: 7 })}> 
        Set 'my-cookie'
      </button>
      {' | '}
      <button onClick={() => cookies.remove('my-cookie')}>Delete 'my-cookie'</button>
    </div>
  );
};

view raw JSON →