Getting, setting and removing cookies on both client and server with next.js
Installations
npm install cookies-next
Developer Guide
Typescript
Yes
Module System
CommonJS, ESM
Node Version
20.11.0
NPM Version
10.2.4
Releases
Contributors
Languages
TypeScript (99.62%)
JavaScript (0.38%)
Developer
andreizanik
Download Statistics
Total Downloads
38,175,244
Last Day
88,636
Last Week
398,414
Last Month
1,787,037
Last Year
21,134,267
GitHub Statistics
663 Stars
150 Commits
49 Forks
4 Watching
3 Branches
15 Contributors
Bundle Size
12.25 kB
Minified
3.72 kB
Minified + Gzipped
Package Meta Information
Latest Version
5.1.0
Package Id
cookies-next@5.1.0
Unpacked Size
84.55 kB
Size
15.73 kB
File Count
35
NPM Version
10.2.4
Node Version
20.11.0
Publised On
15 Jan 2025
Total Downloads
Cumulative downloads
Total Downloads
38,175,244
Last day
-5.6%
88,636
Compared to previous day
Last week
-18%
398,414
Compared to previous week
Last month
1.9%
1,787,037
Compared to previous month
Last year
63.4%
21,134,267
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
cookies-next
A versatile cookie management library for Next.js applications, supporting both client-side and server-side operations.
Features
- Works on client-side, server-side rendering, and API routes
- Supports Next.js 13+ App Router and Server Components
- TypeScript compatible
- Lightweight and easy to use
Installation
For Next.js versions 15 and above, use the latest version of cookies-next:
1npm install --save cookies-next@latest
For Next.js versions 12.2.0 to 14.x, use cookies-next version 4.3.0:
1npm install --save cookies-next@4.3.0
Usage
Importing
For Next.js 15+:
1// For client-side usage 2import { 3 getCookie, 4 getCookies, 5 setCookie, 6 deleteCookie, 7 hasCookie, 8 useGetCookies, 9 useSetCookie, 10 useHasCookie, 11 useDeleteCookie, 12 useGetCookie, 13} from 'cookies-next/client'; 14 15// For server-side usage 16import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next/server';
Also, you can leave the decision of which import to use to the the library itself, by importing from the root:
1import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';
For Next.js 12.2.0 to 13.x:
1import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';
Basic Operations
Set a cookie
1setCookie('key', 'value', options);
Get a cookie
1const value = getCookie('key', options);
Get all cookies
1const cookies = getCookies(options);
Check if a cookie exists
1const exists = hasCookie('key', options);
Delete a cookie
1deleteCookie('key', options);
Client-side Usage
Hooks
Using separate hook for each cookie function:
1'use client'; 2 3import { useGetCookies, useSetCookie, useHasCookie, useDeleteCookie, useGetCookie } from 'cookies-next'; 4 5function ClientComponent() { 6 const setCookie = useSetCookie(); 7 const hasCookie = useHasCookie(); 8 const deleteCookie = useDeleteCookie(); 9 const getCookies = useGetCookies(); 10 const getCookie = useGetCookie(); 11 12 setCookie('key', 'value'); 13 14 return ( 15 <div> 16 <p>hasCookie - {JSON.stringify(hasCookie('key'))}</p> 17 <p>getCookies - {JSON.stringify(getCookies)}</p> 18 <p>getCookie - {getCookie('key')}</p> 19 <button type="button" onClick={() => deleteCookie('key')}> 20 deleteCookie 21 </button> 22 </div> 23 ); 24}
Using one hook that returns all of the cookie functions:
1'use client'; 2 3import { useCookiesNext } from 'cookies-next'; 4 5function ClientComponent() { 6 const { setCookie, hasCookie, deleteCookie, getCookies, getCookie } = useCookiesNext(); 7 8 setCookie('key', 'value'); 9 10 return ( 11 <div> 12 <p>hasCookie - {JSON.stringify(hasCookie('key'))}</p> 13 <p>getCookies - {JSON.stringify(getCookies)}</p> 14 <p>getCookie - {getCookie('key')}</p> 15 <button type="button" onClick={() => deleteCookie('key')}> 16 deleteCookie 17 </button> 18 </div> 19 ); 20}
If you are going to perform actions on cookies inside a useEffect, make sure to add the cookie function returned from the hook to the dependency array.
1const getCookies = useGetCookies(); 2 3useEffect(() => { 4 console.log('getCookies', getCookies()); 5}, [getCookies]);
Client functions
1'use client'; 2 3import { getCookies, setCookie, deleteCookie, getCookie } from 'cookies-next/client'; 4 5function ClientComponent() { 6 /* 7 ❗❗❗ In a client component, it's highly recommended to use cookies-next functions within useEffect or in event handlers; otherwise, you might encounter hydration mismatch errors. - 8 https://react.dev/link/hydration-mismatch. 9 */ 10 11 useEffect(() => { 12 getCookies(); 13 getCookie('key'); 14 setCookie('key', 'value'); 15 deleteCookie('key'); 16 hasCookie('key'); 17 }, []); 18 19 const handleClick = () => { 20 getCookies(); 21 getCookie('key'); 22 setCookie('key', 'value'); 23 deleteCookie('key'); 24 hasCookie('key'); 25 }; 26 27 /* .... */ 28}
Server-side Usage (App Router)
In Server Components:
1import { getCookie, getCookies, hasCookie } from 'cookies-next/server'; 2import { cookies } from 'next/headers'; 3 4export const ServerComponent = async () => { 5 // Read-only operations in Server Components 6 const value = await getCookie('test', { cookies }); 7 const allCookies = await getCookies({ cookies }); 8 const exists = await hasCookie('test', { cookies }); 9 10 // Note: It's not possible to update cookies in Server Components 11 ❌ await setCookie("test", "value", { cookies }); // Won't work 12 ❌ await deleteCookie('test', { cookies }); // Won't work 13 14 return <div>...</div>; 15};
In Server Actions:
1'use server'; 2 3import { cookies } from 'next/headers'; 4import { setCookie, deleteCookie, getCookie, getCookies, hasCookie } from 'cookies-next/server'; 5 6export async function serverAction() { 7 await setCookie('test', 'value', { cookies }); 8 await deleteCookie('test', { cookies }); 9 await getCookie('test', { cookies }); 10 await getCookies({ cookies }); 11 await hasCookie('test', { cookies }); 12}
API Routes (App Router)
1import { cookies } from 'next/headers'; 2import { NextRequest, NextResponse } from 'next/server'; 3import { deleteCookie, getCookie, setCookie, hasCookie, getCookies } from 'cookies-next/server'; 4 5export async function GET(req: NextRequest) { 6 const res = new NextResponse(); 7 await setCookie('test', 'value', { res, req }); 8 await getCookie('test', { res, req }); 9 await getCookies({ res, req }); 10 await deleteCookie('test', { res, req }); 11 await hasCookie('test', { req, res }); 12 13 // Using cookies function 14 await setCookie('test1', 'value', { cookies }); 15 await getCookie('test1', { cookies }); 16 await getCookies({ cookies }); 17 await deleteCookie('test1', { cookies }); 18 await hasCookie('test1', { cookies }); 19 20 return res; 21}
Middleware
1import { NextResponse } from 'next/server'; 2import type { NextRequest } from 'next/server'; 3import { getCookie, setCookie, deleteCookie, hasCookie, getCookies } from 'cookies-next/server'; 4 5export async function middleware(req: NextRequest) { 6 const res = NextResponse.next(); 7 await setCookie('test', 'value', { res, req }); 8 await hasCookie('test', { req, res }); 9 await deleteCookie('test', { res, req }); 10 await getCookie('test', { res, req }); 11 await getCookies({ res, req }); 12 13 return res; 14}
API
setCookie(key, value, options)
Sets a cookie.
1setCookie('key', 'value', options);
getCookie(key, options)
Retrieves a specific cookie.
1const value = getCookie('key', options);
getCookies(options)
Retrieves all cookies.
1const cookies = getCookies(options);
hasCookie(key, options)
Checks if a cookie exists.
1const exists = hasCookie('key', options);
deleteCookie(key, options)
Deletes a cookie.
1deleteCookie('key', options);
Options
req
: Required for server-side operations (except when usingcookies
function)res
: Required for server-side operations (except when usingcookies
function)cookies
: Function fromnext/headers
, used in App Router for server-side operationsdomain
: Specifies the cookie's domainpath
: Specifies the cookie's pathmaxAge
: Specifies the cookie's maximum age in secondshttpOnly
: Sets the HttpOnly flagsecure
: Sets the Secure flagsameSite
: Sets the SameSite attribute ('strict', 'lax', or 'none')
For more detailed options, refer to the cookie specification.
License
MIT
No vulnerabilities found.
Reason
22 commit(s) and 2 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
Found 2/6 approved changesets -- score normalized to 3
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 26 are checked with a SAST tool
Score
4.7
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to cookies-next
next-cookies
get the cookies on both the client & server
next-client-cookies
SSR and client support for Next.js v13 cookies (app directory)
urllib-next
Help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more. Base undici fetch API.
@marshallku/cookies-next
Getting, setting and removing cookies on both client and server with next.js