Max SchmittMS
25th June 2020

Next.js: How to get and set cookies

In a Next.js app, you might find yourself wanting to access cookies during getInitialProps, getServerSideProps or within an API route.

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.

Detecting server-side and client-side access in getInitialProps

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 = !!req
const isBrowser = !req

Client-side cookies with Next.js

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 cookie
// Set a cookie
cookieCutter.set('myCookieName', 'some-value')
// Delete a cookie
cookieCutter.set('myCookieName', '', { expires: new Date(0) })

Server-side cookies with Next.js

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 instance
const cookies = new Cookies(req, res)
// Get a cookie
// Set a cookie
cookies.set('myCookieName', 'some-value', {
httpOnly: true // true by default
// Delete a cookie

Need help on a project?

I'm available for freelance work.
Send me an email! Or find out more about my services.