Next.js Cookies Management
cookies-next is a specialized library designed for managing HTTP cookies within Next.js applications, supporting operations on both the client and server sides, including Server Components and API routes. The current stable version is 6.1.1. It maintains a relatively active release cadence, frequently updating to support new Next.js versions and introduce features like React hooks for client-side state management, including 'reactive hooks' that trigger component re-renders when cookie values change. Key differentiators include its explicit support for Next.js's distinct client and server environments, offering separate import paths for optimized bundles, and providing both static and reactive hooks for flexible client-side usage, distinguishing it from general-purpose cookie libraries.
Common errors
-
Error: Cookies must be used within a server context or be provided manually.
cause Attempting to use server-side cookie functions (e.g., `getCookie` directly in a Server Component without passing the `cookies` object from `next/headers`).fixImport `cookies` from `next/headers` and pass it as an option: `const myCookie = getCookie('mykey', { cookies: cookies() });` -
TypeError: Cannot read properties of undefined (reading 'headers') during SSR
cause This error can occur if server-side cookie functions are called in a context where `req` and `res` objects (or `cookies` from `next/headers`) are not available or not properly passed, especially when using the universal `cookies-next` import.fixEnsure that server-side cookie operations are performed within a `getServerSideProps`, API route, or Server Component where `req`/`res` or the `cookies` object from `next/headers` are accessible and passed to the functions as options. -
Hydration failed because the initial UI does not match what was rendered on the server.
cause Cookies can differ between server-side render and client-side hydration, causing content mismatches if components render differently based on cookie values, especially if cookies are set after the initial server render.fixUse client-side hooks within components marked with 'use client' and ensure any cookie-dependent rendering logic is robustly handled or deferred until the client-side. For SSR, ensure that server-set cookies are consistent or handle variations gracefully.
Warnings
- breaking Version 5.0.0 introduced significant changes to support Next.js 15+, including new explicit client (`cookies-next/client`) and server (`cookies-next/server`) import paths. Applications on Next.js 15+ must update their import statements, or use the root import which attempts to auto-detect the environment.
- breaking Prior to v6.0.0, the `useGetCookies` hook and similar client-side hooks were static and did not trigger component re-renders when cookie values changed externally. Version 6.0.0 changed this behavior, making hooks trigger re-renders to reflect updated cookie states.
- gotcha When using `setCookie` or `deleteCookie` on the server-side with Next.js 13+ App Router, you must explicitly pass the `cookies` object obtained from `next/headers` to the options parameter to correctly manipulate the response headers.
- gotcha Client-side reactive cookie hooks (e.g., `useCookiesNext` when used with the provider) require the `CookiesNextProvider` to be added higher up in your component tree to manage their internal React state and context correctly.
Install
-
npm install cookies-next -
yarn add cookies-next -
pnpm add cookies-next
Imports
- getCookie, setCookie
const { getCookie, setCookie } = require('cookies-next')import { getCookie, setCookie } from 'cookies-next' - getCookie, setCookie (client-side)
import { getCookie, setCookie } from 'cookies-next'import { getCookie, setCookie } from 'cookies-next/client' - getCookie, setCookie (server-side)
import { getCookie, setCookie } from 'cookies-next'import { getCookie, setCookie } from 'cookies-next/server' - useCookiesNext
import { useCookiesNext } from 'cookies-next'
Quickstart
import { getCookie, setCookie, deleteCookie } from 'cookies-next/server';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
// Example: API Route for server-side operations (Next.js App Router)
export async function GET(request: Request) {
const serverCookies = cookies(); // Access Next.js headers cookies
const myCookie = getCookie('my-server-cookie', { cookies: serverCookies });
console.log('Server-side myCookie:', myCookie);
if (!myCookie) {
setCookie('my-server-cookie', 'server-value', {
cookies: serverCookies,
maxAge: 60 * 60 * 24,
path: '/',
httpOnly: true
});
return NextResponse.json({ message: 'Cookie set!', value: 'server-value' });
}
return NextResponse.json({ message: 'Cookie already exists', value: myCookie });
}
// Example: Client Component usage (for demonstration, this would be in a '.tsx' file with 'use client')
// 'use client';
// import { useSetCookie, useGetCookie, useDeleteCookie } from 'cookies-next';
// import { useEffect } from 'react';
// function ClientCookieDemo() {
// const setClientCookie = useSetCookie();
// const getClientCookie = useGetCookie();
// const deleteClientCookie = useDeleteCookie();
// useEffect(() => {
// setClientCookie('my-client-cookie', 'client-value', { maxAge: 3600 });
// const val = getClientCookie('my-client-cookie');
// console.log('Client-side my-client-cookie:', val);
// }, [setClientCookie, getClientCookie]);
// return (
// <div>
// <p>Client-side cookie operations demonstrated.</p>
// <button onClick={() => deleteClientCookie('my-client-cookie')}>Delete Client Cookie</button>
// </div>
// );
// }
// export default ClientCookieDemo;