Next Cookies
Tiny little function for getting cookies on both client & server with next.js.
This enables easy client-side and server-side rendering of pages that depend on cookies.
Installation
yarn add next-cookies
or
npm install --save next-cookies
Usage
Read all cookies:
const allCookies = ;allCookies will be an object with keys for each cookie.
The ctx object is passed to your getInitialProps function by next.js.
Read a single cookie:
const myCookie = ;or
const myCookie = myCookie;The ctx object is passed to your getInitialProps function by next.js.
Set a cookie:
This library does not support setting cookies. However, this is how to do it in client-side code:
documentcookie = `foo=bar; path=/`;This sets a cookie named foo to the value bar.
The path portion is optional but usually desired.
An expiration date may be appended (see below), otherwise the cookie will be deleted whenever the browser is closed.
Delete a cookie:
This library does not support deleting cookies. However, this is how to do it in client-side code:
documentcookie = `foo=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT`;The value doesn't matter, although the path does. The expiration date must be in the past.
Complete Example
Component static async { return initialName: name || '' } { superprops; thisstate = name: propsinitialName || ''; thishandleChange = thishandleChange; thisreset = thisreset; } { const newName = eventtargetvalue; this; documentcookie = `name=; path=/`; } { this; documentcookie = 'name=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT'; } { return <div> <p>Hi thisstatename</p> <p>Change cookie: <input type="text" placeholder="Your name here" value=thisstatename onChange=thishandleChange />! </p> <p>Delete cookie: <button onClick=thisreset>Reset</button></p> </div> ; } See, also, the test app: https://github.com/matthewmueller/next-cookies/blob/master/tests/test-app/pages/cookies.js
More Information
- https://www.npmjs.com/package/universal-cookie
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
- https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
- https://tools.ietf.org/html/rfc6265
License
MIT