next-universal-cookies
v1.1.1
Published
Cookie helpers/utils for Next.js applications
Downloads
114
Readme
🍪 next-universal-cookies 🍪
A proper collection of cookie helpers for use on both the client and server in Next.js applications
Installation
npm
npm install --save next-universal-cookies
or yarn
yarn add next-universal-cookies
Usage
Server
Any of the set of helpers can be utilized in getServerSideProps
, getInitialProps
, API routes.
For either getServerSideProps
| getInitialProps
, just pass in the context object as the first argument.
If using the helpers in next API routes, pass req
and res
as an object in the first parameter:
import { parseCookies } from 'next-universal-cookies';
const cookies = parseCookies({ req, res })
// Parsing
import { getCookieValue, parseCookies } from 'next-universal-cookies';
// Parse all cookies
const cookies = parseCookies(ctx);
// Parse and get single cookie value by name
const cookieValue = getCookieValue(ctx, 'cookie'); // returns string
// Parse and get multple cookie values by name
const { cookie, cookie2 } = getCookieValue(ctx, ['cookie', 'cookie2']); // returns object of values
// Setting
import { setCookie } from 'next-universal-cookies';
// Set single cookie
setCookie(ctx, {
name: 'cookie',
value: 'cookie-value',
options: {
path: '/my-path',
sameSite: 'strict'
}
});
// or Set multiple cookies
setCookie(ctx, [
{
name: 'cookie',
value: 'cookie-value',
options: {
path: '/my-path',
sameSite: 'strict',
},
},
{
name: 'cookie-too',
value: 'cookie-value-too',
},
]);
// Destroying
import { destroyCookie } from 'next-universal-cookies';
// Destory cookie with name 'cookie'
destroyCookie(ctx, 'cookie');
Client
The cookie helpers can also be utilized on the client. The function's input signature
is slightly altered when used client side. The context
object is no longer required as
an argument.
// Parsing
import { getCookieValue, parseCookies } from 'next-universal-cookies';
// Parse all cookies
const cookies = parseCookies();
// Parse and get single cookie value
const cookieValue = getCookieValue('cookie'); // returns string
// Parse and get multple cookie values by name
const { cookie, cookie2 } = getCookieValue(['cookie', 'cookie2']); // returns object of values
// Setting
import { setCookie } from 'next-universal-cookies';
// Set single cookie
setCookie({
name: 'cookie',
value: 'cookie-value',
options: {
path: '/my-path',
sameSite: 'strict'
}
});
// or Set multiple cookies
setCookie([
{
name: 'cookie',
value: 'cookie-value',
options: {
path: '/my-path',
sameSite: 'strict',
},
},
{
name: 'cookie-too',
value: 'cookie-value-too',
},
]);
// Destroying
import { destroyCookie } from 'next-universal-cookies';
// Destory cookie with name 'cookie'
destroyCookie('cookie');
Contributors
This project follows the all-contributors specification. Contributions of any kind welcome!
LICENSE
MIT