πͺ Cookies Universal for NextJS App Route

An utility that can help you to handle the Cookies in NextJS App Route with every context (both Server or Client) πͺπ₯
All supported to NextJS App Route
Table of Contents
Live Demo
You can see Live Demo here
Getting Started
Install
NPM
npm i next-cookies-universal
Yarn
yarn add next-cookies-universal
Usage
Initialize
import Cookies from 'next-cookies-universal';
const ServerCookies = Cookies('server');
const ClientCookies = Cookies('client');
Client Component
'use client';
import Cookies from 'next-cookies-universal';
const MyClientComponent = () => {
const cookies = Cookies('client');
const handleClick = () => {
cookies.set('my_token', 'my_token_value');
};
const handleClickWithExpiry = () => {
cookies.set('my_token', 'my_token_value', {
maxAge: 60 * 60,
path: '/'
});
};
const handleClickWithExpiresDate = () => {
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 7);
cookies.set('my_token', 'my_token_value', {
expires: expiryDate,
path: '/'
});
};
return (
<div>
<button onClick={handleClick}>
Click to set cookies
</button>
<button onClick={handleClickWithExpiry}>
Click to set cookies with maxAge
</button>
<button onClick={handleClickWithExpiresDate}>
Click to set cookies with expires date
</button>
</div>
);
};
Server Component
import Cookies from 'next-cookies-universal';
const MyServerComponent = async() => {
const cookies = Cookies('server');
const myToken = await cookies.get('my_token');
const data = await fetch('http://your.endpoint', {
headers: {
Authentication: `Bearer ${myToken}`
}
}).then(response => response.json());
return (
<div>
<p>Cookies Value: <strong>{myToken}</strong></p>
<code>
{JSON.stringify(data)}
</code>
</div>
);
};
Note: if you want to set cookies in Server, you not to allowed to set it on Server Component, you should do that in Server Actions.
import Cookies from 'next-cookies-universal';
const MyServerComponent = async() => {
const cookies = Cookies('server');
await cookies.set('my_token', 'my_token_value');
const myToken = await cookies.get('my_token');
return (
<div>
<p>Cookies Value: <strong>{myToken}</strong></p>
<code>
{JSON.stringify(data)}
</code>
</div>
);
};
Server Actions
With Server Component
import Cookies from 'next-cookies-universal';
async function setFromAction(formData: FormData) {
'use server';
const cookies = Cookies('server');
await cookies.set('my_token', formData.get('cookie-value'));
}
function Form() {
return (
<div>
<form action={setFromAction}>
<input type="text" name="cookie-value" />
<div>
<button type="submit">
Set Your cookies
</button>
</div>
</form>
</div>
);
}
With Client Component
'use server';
export async function setFromAction(formData: FormData) {
const cookies = Cookies('server');
await cookies.set('my_token', formData.get('cookie-value'));
}
'use client';
import { setFromAction } from './action.ts';
function Form() {
return (
<div>
<form action={setFromAction}>
<input type="text" name="cookie-value" />
<div>
<button type="submit">
Set Your cookies
</button>
</div>
</form>
</div>
);
}
Cookie Options
Setting Cookies with Expiration
You can set cookies with various expiration options using the options
parameter:
'use client';
import Cookies from 'next-cookies-universal';
const cookies = Cookies('client');
cookies.set('session_token', 'abc123', {
maxAge: 60 * 60,
path: '/'
});
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
cookies.set('user_preference', 'dark_mode', {
expires: tomorrow,
path: '/',
secure: true,
sameSite: 'strict'
});
cookies.set('remember_me', 'true', {
maxAge: 365 * 24 * 60 * 60,
path: '/'
});
const specificDate = new Date('2024-12-31T23:59:59Z');
cookies.set('campaign_banner', 'hidden', {
expires: specificDate,
path: '/'
});
Server Actions with Cookie Options
import Cookies from 'next-cookies-universal';
async function setTokenWithExpiry(formData: FormData) {
'use server';
const cookies = Cookies('server');
const token = formData.get('token');
await cookies.set('auth_token', token, {
maxAge: 7 * 24 * 60 * 60,
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
const sessionExpiry = new Date();
sessionExpiry.setHours(sessionExpiry.getHours() + 2);
await cookies.set('session_id', 'session_123', {
expires: sessionExpiry,
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
});
}
Important Notes
- maxAge: Specifies the cookie expiration time in seconds (relative to current time)
- expires: Specifies the exact date and time when the cookie should expire (absolute time)
- Client-side:
- The
maxAge
option is automatically converted to an expires
Date object for compatibility with js-cookie
- The
expires
option accepts a Date object directly
- Server-side: Uses Next.js built-in cookie handling which supports both
maxAge
and expires
directly
- Choosing between maxAge and expires:
- Use
maxAge
for relative expiration (e.g., "expire in 1 hour")
- Use
expires
for absolute expiration (e.g., "expire on December 31st")
- Security: Always use
secure: true
and appropriate sameSite
settings in production
API Reference
export type ICookiesContext = 'server'|'client';
export interface IClientCookies {
set<T = string>(
key: string,
value: T,
options?: ICookiesOptions
): void;
get<T = string>(key: string): T;
remove(key: string, options?: ICookiesOptions): void;
has(key: string): boolean;
clear(): void;
}
export interface IServerCookies {
set<T = string>(
key: string,
value: T,
options?: ICookiesOptions
): Promise<void>;
get<T = string>(key: string): Promise<T>;
remove(key: string, options?: ICookiesOptions): Promise<void>;
has(key: string): Promise<boolean>;
clear(): Promise<void>;
}
function Cookies(context: 'client'): IClientCookies;
function Cookies(context: 'server'): IServerCookies;
for ICookiesOptions
API, we use CookieSerializeOptions
from DefinetlyTyped
Publishing
- Before pushing your changes to Github, make sure that
version
in package.json
is changed to newest version. Then run npm install
for synchronize it to package-lock.json
- After your changes have been merged on branch
main
, you can publish the packages by creating new Relase here: https://github.com/gadingnst/next-cookies-universal/releases/new
- Create new
tag
, make sure the tag
name is same as the version
in package.json
.
- You can write Release title and notes here. Or you can use auto-generated release title and notes.
- Click
Publish Release
button, then wait the package to be published.
License
next-cookies-universal
is freely distributable under the terms of the MIT license.
Feedbacks and Issues
Feel free to open issues if you found any feedback or issues on next-cookies-universal
. And feel free if you want to contribute too! π
Support
Global

Indonesia
Built with β€οΈ by Sutan Gading Fadhillah Nasution on 2023