@hasparus/nookies
v2.3.2
Published
A set of cookie helpers for Next.js
Downloads
15
Maintainers
Readme
nookies :cookie: :cookie: :cookie:
A collection of cookie helpers for Next.js
- SSR support, for setter, parser and destroy
- super light
- perfect for authentication
Setting and destroying cookies also works on server-side.
Quick start
npm install --save nookies
SSR cookies
import { parseCookies, setCookie, destroyCookie } from 'nookies'
export default class Me extends React.Component {
static async getInitialProps(ctx) {
// Parse
parseCookies(ctx)
// Set
setCookie(ctx, 'token', token, {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
destroyCookie(ctx, 'token')
}
render() {
return <div>My profile</div>
}
}
OR
import nookies from 'nookies'
export default class Me extends React.Component {
static async getInitialProps(ctx) {
// Parse
nookies.get(ctx)
// Set
nookies.set(ctx, 'token', token, {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
nookies.destroy(ctx, 'token')
}
render() {
return <div>My profile</div>
}
}
Cookies on the client
import { parseCookies } from 'nookies'
export default class Me extends React.Component {
handleClick = () => {
// Simply omit context parameter.
// Parse
const cookies = parseCookies()
console.log({ cookies })
// Set
setCookie(null, 'token', token, {
maxAge: 30 * 24 * 60 * 60,
path: '/',
})
// Destroy
destroyCookie(null, 'token')
}
render() {
return <button onClick={this.handleClick}>Click Me!</button>
}
}
Reference
For client side usage, omit the
ctx
parameter. You can do so by setting it to an empty object ({}
).
parseCookies(ctx, options)
or cookies.get(ctx, options)
- ctx:
Next.js context
- options:
- decode:
a custom resolver function (default: decodeURIComponent)
- decode:
setCookie(ctx, name, value, options)
or cookies.set(ctx, name, value, options)
- ctx:
(Next.js context)
- name: cookie name
- value: cookie value
- options:
- domain
- encode
- expires
- httpOnly
- maxAge
- path
- sameSite
- secure
destroyCookie(ctx, name, options)
or cookies.destroy(ctx, 'token', options)
- ctx: (Next.js context)
- name: cookie name
- options:
- domain
- path
License
MIT