{"id":10670,"library":"cookies-next","title":"Next.js Cookies Management","description":"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.","status":"active","version":"6.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/andreizanik/cookies-next","tags":["javascript","js","cookies","cookie","next","next.js","nextjs","destory","parse","typescript"],"install":[{"cmd":"npm install cookies-next","lang":"bash","label":"npm"},{"cmd":"yarn add cookies-next","lang":"bash","label":"yarn"},{"cmd":"pnpm add cookies-next","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for Next.js specific client/server context and rendering patterns.","package":"next","optional":false},{"reason":"Required for React hooks and component integration in Next.js applications.","package":"react","optional":false}],"imports":[{"note":"For universal usage (auto-detects client/server). Modern Next.js apps use ESM; CommonJS `require` is generally incorrect for contemporary usage.","wrong":"const { getCookie, setCookie } = require('cookies-next')","symbol":"getCookie, setCookie","correct":"import { getCookie, setCookie } from 'cookies-next'"},{"note":"Explicitly imports client-side functions. Recommended for client components in Next.js 15+ to ensure tree-shaking and avoid server-side code bundles.","wrong":"import { getCookie, setCookie } from 'cookies-next'","symbol":"getCookie, setCookie (client-side)","correct":"import { getCookie, setCookie } from 'cookies-next/client'"},{"note":"Explicitly imports server-side functions. Recommended for Server Components or API routes in Next.js 15+ for clarity and bundle optimization.","wrong":"import { getCookie, setCookie } from 'cookies-next'","symbol":"getCookie, setCookie (server-side)","correct":"import { getCookie, setCookie } from 'cookies-next/server'"},{"note":"A client-side hook providing all cookie functions. Requires 'use client' directive for the component.","symbol":"useCookiesNext","correct":"import { useCookiesNext } from 'cookies-next'"}],"quickstart":{"code":"import { getCookie, setCookie, deleteCookie } from 'cookies-next/server';\nimport { cookies } from 'next/headers';\nimport { NextResponse } from 'next/server';\n\n// Example: API Route for server-side operations (Next.js App Router)\nexport async function GET(request: Request) {\n  const serverCookies = cookies(); // Access Next.js headers cookies\n  const myCookie = getCookie('my-server-cookie', { cookies: serverCookies });\n  console.log('Server-side myCookie:', myCookie);\n\n  if (!myCookie) {\n    setCookie('my-server-cookie', 'server-value', { \n      cookies: serverCookies, \n      maxAge: 60 * 60 * 24, \n      path: '/',\n      httpOnly: true\n    });\n    return NextResponse.json({ message: 'Cookie set!', value: 'server-value' });\n  }\n  \n  return NextResponse.json({ message: 'Cookie already exists', value: myCookie });\n}\n\n// Example: Client Component usage (for demonstration, this would be in a '.tsx' file with 'use client')\n// 'use client';\n// import { useSetCookie, useGetCookie, useDeleteCookie } from 'cookies-next';\n// import { useEffect } from 'react';\n\n// function ClientCookieDemo() {\n//   const setClientCookie = useSetCookie();\n//   const getClientCookie = useGetCookie();\n//   const deleteClientCookie = useDeleteCookie();\n\n//   useEffect(() => {\n//     setClientCookie('my-client-cookie', 'client-value', { maxAge: 3600 });\n//     const val = getClientCookie('my-client-cookie');\n//     console.log('Client-side my-client-cookie:', val);\n//   }, [setClientCookie, getClientCookie]);\n\n//   return (\n//     <div>\n//       <p>Client-side cookie operations demonstrated.</p>\n//       <button onClick={() => deleteClientCookie('my-client-cookie')}>Delete Client Cookie</button>\n//     </div>\n//   );\n// }\n// export default ClientCookieDemo;","lang":"typescript","description":"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."},"warnings":[{"fix":"For Next.js 15+, update imports to `from 'cookies-next/client'` for client components and `from 'cookies-next/server'` for server components/API routes. Alternatively, use `from 'cookies-next'` but be aware of potential bundle size implications for older Next.js versions.","message":"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.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Review components using client-side cookie hooks (`useGetCookies`, `useGetCookie`, etc.) after upgrading to v6.0.0. If you relied on the static behavior, you might experience unexpected re-renders. Consider using reactive hooks where explicit re-rendering is desired or adjust component logic.","message":"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.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Ensure you import `cookies` from `next/headers` and pass `{ cookies }` as an option to `setCookie` or `deleteCookie` when operating in Server Components or API routes (e.g., `setCookie('key', 'value', { cookies });`).","message":"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.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Wrap your application or relevant client components with `CookiesNextProvider` to enable the reactive functionality of hooks like `useCookiesNext` or those imported from `cookies-next/client`.","message":"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.","severity":"gotcha","affected_versions":">=6.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Import `cookies` from `next/headers` and pass it as an option: `const myCookie = getCookie('mykey', { cookies: cookies() });`","cause":"Attempting to use server-side cookie functions (e.g., `getCookie` directly in a Server Component without passing the `cookies` object from `next/headers`).","error":"Error: Cookies must be used within a server context or be provided manually."},{"fix":"Ensure 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.","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.","error":"TypeError: Cannot read properties of undefined (reading 'headers') during SSR"},{"fix":"Use 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.","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.","error":"Hydration failed because the initial UI does not match what was rendered on the server."}],"ecosystem":"npm"}