nookies :cookie:
A collection of cookie helpers for Next.js
Features
- ✨ SSR support, for setter, parser and destroy
- ⚙️ Custom Express server support
- 🪶 super light
- 🛡 perfect for authentication
Setting and destroying cookies also works on server-side.
Quick start
yarn add nookies
You can play with the example code here.
ServerSide cookies
import nookies from 'nookies'
export default function Me() {
return <div>My profile</div>
}
export async function getServerSideProps(ctx) {
const cookies = nookies.get(ctx)
nookies.set(ctx, 'fromGetInitialProps', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
return { cookies }
}
Client-only Cookies
import { parseCookies, setCookie, destroyCookie } from 'nookies'
function handleClick() {
const cookies = parseCookies()
console.log({ cookies })
setCookie(null, 'fromClient', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
}
export default function Me() {
return <button onClick={handleClick}>Set Cookie</button>
}
Custom Express server cookies
const express = require('express');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const { parseCookies, setCookie, destroyCookie } = require('nookies');
app.prepare()
.then(() => {
const server = express();
server.get('/page', (req, res) => {
const parsedCookies = parseCookies({ req });
setCookie({ res }, 'fromServer', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/page',
});
return handle(req, res);
});
);
Reference
For client side usage, omit the ctx
parameter. You can do so by setting it to an empty object ({}
), null
or undefined
.
parseCookies(ctx, options)
or nookies.get(ctx, options)
- ctx:
Next.js context
|| (Express request object)
- options:
- decode:
a custom resolver function (default: decodeURIComponent)
setCookie(ctx, name, value, options)
or nookies.set(ctx, name, value, options)
Don't forget to end your response on the server with res.send()
.
- ctx:
(Next.js context)
|| (Express request object)
- name: cookie name
- value: cookie value
- options:
- domain
- encode
- expires
- httpOnly
- maxAge
- path
- sameSite
- secure
destroyCookie(ctx, name, options)
or nookies.destroy(ctx, 'token', options)
Don't forget to end your response on the server with res.send()
. This might be the reason your cookie isn't removed.
- ctx:
(Next.js context)
|| (Express response object)
- name: cookie name
- options:
License
MIT