Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
cookies-next
Advanced tools
Set, Get, Remove cookies on both client and server side with Next.js
The cookies-next npm package is a utility for handling cookies in Next.js applications. It provides simple methods to set, get, and delete cookies both on the client and server side.
Set a Cookie
This feature allows you to set a cookie with a specified name and value. You can also set additional options such as maxAge. The code sample demonstrates how to set a cookie both on the server side and client side.
const { setCookie } = require('cookies-next');
// On the server side
export function handler(req, res) {
setCookie('token', '123456', { req, res, maxAge: 60 * 60 * 24 });
res.end('Cookie set');
}
// On the client side
setCookie('token', '123456', { maxAge: 60 * 60 * 24 });
Get a Cookie
This feature allows you to retrieve the value of a specified cookie. The code sample demonstrates how to get a cookie both on the server side and client side.
const { getCookie } = require('cookies-next');
// On the server side
export function handler(req, res) {
const token = getCookie('token', { req, res });
res.end(`Token: ${token}`);
}
// On the client side
const token = getCookie('token');
console.log(`Token: ${token}`);
Delete a Cookie
This feature allows you to delete a specified cookie. The code sample demonstrates how to delete a cookie both on the server side and client side.
const { deleteCookie } = require('cookies-next');
// On the server side
export function handler(req, res) {
deleteCookie('token', { req, res });
res.end('Cookie deleted');
}
// On the client side
deleteCookie('token');
The 'cookie' package is a simple, lightweight library for parsing and serializing cookies. Unlike cookies-next, it does not provide built-in support for Next.js and requires more manual handling of cookies.
The 'universal-cookie' package provides a universal way to handle cookies in JavaScript, supporting both client and server environments. It is more versatile than cookies-next but requires additional setup to work seamlessly with Next.js.
The 'js-cookie' package is a popular library for handling cookies in the browser. It is very easy to use but does not support server-side operations out of the box, making it less suitable for Next.js applications compared to cookies-next.
A versatile cookie management library for Next.js applications, supporting both client-side and server-side operations.
For Next.js versions 15 and above, use the latest version of cookies-next:
npm install --save cookies-next@latest
For Next.js versions 12.2.0 to 14.x, use cookies-next version 4.3.0:
npm install --save cookies-next@4.3.0
For Next.js 15+:
// For client-side usage
import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next/client';
// For server-side usage
import { 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:
import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';
For Next.js 12.2.0 to 13.x:
import { getCookie, getCookies, setCookie, deleteCookie, hasCookie } from 'cookies-next';
setCookie('key', 'value', options);
const value = getCookie('key', options);
const cookies = getCookies(options);
const exists = hasCookie('key', options);
deleteCookie('key', options);
'use client';
import { getCookies, setCookie, deleteCookie, getCookie } from 'cookies-next/client';
function ClientComponent() {
/*
❗❗❗ 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. -
https://react.dev/link/hydration-mismatch.
*/
useEffect(() => {
getCookies();
getCookie('key');
setCookie('key', 'value');
deleteCookie('key');
hasCookie('key');
}, []);
const handleClick = () => {
getCookies();
getCookie('key');
setCookie('key', 'value');
deleteCookie('key');
hasCookie('key');
};
/* .... */
}
// Use anywhere in client-side code
In Server Components:
import { getCookie, getCookies, hasCookie } from 'cookies-next/server';
import { cookies } from 'next/headers';
export const ServerComponent = async () => {
// Read-only operations in Server Components
const value = await getCookie('test', { cookies });
const allCookies = await getCookies({ cookies });
const exists = await hasCookie('test', { cookies });
// Note: It's not possible to update cookies in Server Components
❌ setCookie("test", "value", { cookies }); // Won't work
❌ deleteCookie('test', { cookies }); // Won't work
return <div>...</div>;
};
In Server Actions:
'use server';
import { cookies } from 'next/headers';
import { setCookie, deleteCookie, getCookie, getCookies, hasCookie } from 'cookies-next/server';
export async function serverAction() {
await setCookie('test', 'value', { cookies });
await deleteCookie('test', { cookies });
await getCookie('test', { cookies });
await getCookies({ cookies });
await hasCookie('test', { cookies });
}
import { cookies } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { deleteCookie, getCookie, setCookie, hasCookie, getCookies } from 'cookies-next/server';
export async function GET(req: NextRequest) {
const res = new NextResponse();
await setCookie('test', 'value', { res, req });
await getCookie('test', { res, req });
await getCookies({ res, req });
await deleteCookie('test', { res, req });
await hasCookie('test', { req, res });
// Using cookies function
await setCookie('test1', 'value', { cookies });
await getCookie('test1', { cookies });
await getCookies({ cookies });
await deleteCookie('test1', { cookies });
await hasCookie('test1', { cookies });
return res;
}
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getCookie, setCookie, deleteCookie, hasCookie, getCookies } from 'cookies-next/server';
export async function middleware(req: NextRequest) {
const res = NextResponse.next();
await setCookie('test', 'value', { res, req });
await hasCookie('test', { req, res });
await deleteCookie('test', { res, req });
await getCookie('test', { res, req });
await getCookies({ res, req });
// Note: cookies function from next/headers cannot be used in middleware
❌ setCookie('test', 'value', { cookies }); // Won't work
return res;
}
Sets a cookie.
setCookie('key', 'value', options);
Retrieves a specific cookie.
const value = getCookie('key', options);
Retrieves all cookies.
const cookies = getCookies(options);
Checks if a cookie exists.
const exists = hasCookie('key', options);
Deletes a cookie.
deleteCookie('key', options);
req
: Required for server-side operations (except when using cookies
function)res
: Required for server-side operations (except when using cookies
function)cookies
: Function from next/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.
MIT
FAQs
Set, Get, Remove cookies on both client and server side with Next.js
The npm package cookies-next receives a total of 413,960 weekly downloads. As such, cookies-next popularity was classified as popular.
We found that cookies-next demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.