A set of cookie helpers for Next.js
A collection of cookie helpers for Next.js
Setting and destroying cookies also works on server-side.
yarn add nookies
You can play with the example code here.
import nookies from 'nookies'
export default function Me() {
return
}
export async function getServerSideProps(ctx) {
// Parse
const cookies = nookies.get(ctx)
// Set
nookies.set(ctx, 'fromGetInitialProps', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
// nookies.destroy(ctx, 'cookieName')
return { cookies }
}import { parseCookies, setCookie, destroyCookie } from 'nookies'
function handleClick() {
// Simply omit context parameter.
// Parse
const cookies = parseCookies()
console.log({ cookies })
// Set
setCookie(null, 'fromClient', 'value', {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
// destroyCookie(null, 'cookieName')
}
export default function Me() {
return <button onClick={handleClick}>Set Cookie</button>
}…For client side usage, omit the
ctxparameter. You can do so by setting it to an empty object ({}),nullorundefined.
parseCookies(ctx, options) or nookies.get(ctx, options)Next.js context || (Express request object)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().
(Next.js context) || (Express request object)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.
(Next.js context) || (Express response object)MIT
No open issues yet, or sync has not completed.