In a Next.js app, you might find yourself wanting to access cookies during getInitialProps
, getServerSideProps
or within an API route.
If you're looking to implement HTTP-only cookies for authentication in Next.js, I've published a separate post on that topic.
Next.js does not expose any helpers to deal with cookies itself, but luckily there are some great lightweight packages to help us out here.
Remember that getInitialProps
in a Next.js app can run on both server and client. You can detect where you're running by simply checking for the existence of ctx.req
:
Homepage.getInitialProps = ({ req }) => {const isServer = !!reqconst isBrowser = !req}
To easily get and set cookies in the browser with Next.js, I recommend using the excellent and tiny cookie-cutter module. It weighs only 700 bytes minified, has no external dependencies and works even on super-old browsers.
import cookieCutter from 'cookie-cutter'// Get a cookiecookieCutter.get('myCookieName')// Set a cookiecookieCutter.set('myCookieName', 'some-value')// Delete a cookiecookieCutter.set('myCookieName', '', { expires: new Date(0) })
On the server, you can use the cookies module to easily get and set cookies on the request
/ response
objects.
import Cookies from 'cookies'Homepage.getInitialProps = ({ req, res }) => {// Create a cookies instanceconst cookies = new Cookies(req, res)// Get a cookiecookies.get('myCookieName')// Set a cookiecookies.set('myCookieName', 'some-value', {httpOnly: true // true by default})// Delete a cookiecookies.set('myCookieName')}
Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.
When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.
If you need help on a project, feel free to contact me.
To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.