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.

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.

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
Image of my head

About the author

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, please reach out and let's work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.