Products
Manager UI
Next.js & Cookies
How to work with cookies in Next.js
This tutorial assumes you have a Next.js project and are familiar with NPM and React. Final code example is available on Github: https://github.com/zesty-io/livestream-examples/blob/main/nextjs-example-website/pages/cookie-example.js
What you'll learn in the Next.js Cookies Tutorial
- What are cookies?
- How set cookies with Next.js
- How get cookies with Next.js
- How to use cookies to personalize the page
What are Cookies?
Cookies are small data storage objects that can written to and accessed from the browser during a user session.
Cookies are used for tracking, personalization, app-memory, marketing recognition etc.. There isn't specific scope to which cookies can be used for. Common examples are tracking IDs, login session tokens, and filter option memory.
How to set cookies with Next.js
To access and write cookies in a Next.js React app, we are going to leverage the NPM package https://www.npmjs.com/package/cookies-next to cut down on writing custom code.
Thank you https://github.com/andreizanik for the package!
To get started, install cookies-next
using NPM or Yarn to your project.
After installing cookies-next
to your project, open up the Next.js /page
component you want to test cookies in. We will test on homepage.js.
In this example, we will write the cookie using client side code, this will work for both static site generation and server side rendering. To run code after the DOM renders, we will use React's useEffect hook.
How access (get) cookies with Next.js
To access the cookie we set, we will use both React's useEffect and React's useState hook connect values we extract from the client side to our JSX output. Nothing to install here as useHook and useEffect are both part of React.
A ternary conditional is used to use a fallback value if the cookie isn't set.
Using cookies to personalize a Next.js page
Using the same example as above, we will leverage the written cookie value to change the presentation output, and also connect that change to a select input, which will update or write the cookie.
Connect with Content Experts
Book a free 15-minute consultation with a content expert. Discuss your application, pain points and requirements. Understand how Zesty's lower total cost of ownership, features, functionality can elevate your business by creating extraordinary digital experiences.
Trusted By
G2 MOMENTUM LEADER