Next.js Cookies Management

6.1.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates server-side cookie management within a Next.js App Router API route, including setting, getting, and deleting cookies. It shows how to integrate with Next.js's native `cookies` function for server contexts.

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;

view raw JSON →