How to use cookies in Next.js for server side and client side

Getting started

To use cookies in Next.js, we need to install 2 npm packages: cookies and cookie-cutter. cookies allows us to set the cookie from the server side while the cookie-cutter lets us access the set cookie from the client side.

npm install cookies cookie-cutter

Setting up the utils module for cookies which work both with server side and client side

Giving your app access to the server side cookies

We will use getInitialProps in our pages/_app.js file to check if the user already has a valid cookie on the server side before rendering the app. An alternative to this approach is using getServerSideProps.

Giving your app access to the client side cookies

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

JavaScript Algorithms: Valid Parentheses (LeetCode)

Tailwind CSS in HTML starter via NPM

Improve Your Bad React and TypeScript Programming Habits

Improve Your Bad React and TypeScript Programming Habits | Tomoe

Day 81 Training at Ryaz: Working on a project.

Demystifying Hooks

Deployment with Heroku — Part #10A of 11

Deploying React App on Apache Tomcat

How I built a Twitter bot that tweets 100-year-old New York Times articles

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Artem Misiura

Artem Misiura

More from Medium

Rails::API and React — My Template

Lightweight Alternatives to Redux

How to test a React App, with Jest and react-testing-library

Next JS (The React Framework) - part 1: Routing