In a Next.js app, you might find yourself wanting to access cookies during server-side rendering (using getServerSideProps
or getInitialProps
), within an API route or when a user accesses a static page that was generated using getStaticProps
.
If you're looking to implement HTTP-only cookies for authentication in Next.js, I've published a separate post on that topic.
When you're using Next.js as a static site generator, you can use Next.js middleware to get and set cookies.
You can't access cookies directly in getStaticProps
because that function runs at build time and not at the time of the request.
middleware.ts
import { NextResponse, NextRequest } from 'next/server'export function middleware(request: NextRequest) {// Get a cookierequest.cookies.get('myCookieName')?.value// Get all cookiesrequest.cookies.getAll()// To change a cookie, first create a responseconst response = NextResponse.next()// Set a cookieresponse.cookies.set('myCookieName', 'some-value')// Setting a cookie with additional optionsresponse.cookies.set({name: 'myCookieName',value: 'some-value',httpOnly: true})// Delete a cookieresponse.cookies.delete('myCookieName')return response}
This also works for server-rendered pages.
Just be aware that middleware runs for every page in your project, so if you only want to get/set cookies for certain paths, you might want to use a matcher or manually check the pathname (request.nextUrl.pathname
) in the middleware.
When server-rendering a page in Next.js, you'll most-likely use getServerSideProps
.
You can then use the cookies module to easily get and set cookies on the request
/ response
objects:
import Cookies from 'cookies'Homepage.getServerSideProps = ({ 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')}
Modern Next.js apps don't usually use getInitialProps
.
When you do, you can get and set cookies on the server the same way as in getServerSideProps
.
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 = !reqif (isServer) {// Get/set cookies server-side} else {// Get/set cookies client-side}}
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) })
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.