Sentry Answers>Next.js>

Is it possible to set a server-side cookie in Next.js?

Is it possible to set a server-side cookie in Next.js?

Matthew C.

The Problem

You want to set a cookie on the server in your Next.js application. For example, you may have an e-commerce website that has Google adverts. If a user clicks on an ad for a summer sale page on your e-commerce website, the e-commerce website is opened with the following campaign parameter in the URL:

Click to Copy
https://www.yourecommercewebsite/shop?campaign=summer_sale

You want to save this information in a cookie to personalize the user’s next browsing sessions by adding more content relevant to the summer sale when they visit your e-commerce website again.

How do you set the cookie on the server side to store this information?

The Solution

You can set a server-side cookie in Next.js. If you are using the Next.js app directory, use the Next.js cookies function.

The cookies function allows you to create cookies in a Server Action or a Route Handler.

For example, if you want to set a cookie based on URL parameters, you can create a page in your src/app folder:

Click to Copy
import Campaigns from "@/components/Campaigns"; export default function Home() { return <Campaigns />; }

Then create a Client Component in src/components/Campaigns.tsx that can read the current URL and call a Server Action to create a campaign cookie:

Click to Copy
import { createCampaignCookie } from "@/app/actions"; import { useSearchParams } from "next/navigation"; export default function Campaigns() { const searchParams = useSearchParams(); function handleClick() { const campaign = searchParams.get("campaign"); createCampaignCookie(campaign || ""); } return <button onClick={handleClick}>View all Summer Sale deals</button>; }

In this example code, the useSearchParams Client Component hook is used to read the URL query string. It gets the value for the "campaign" search parameter. When a user clicks on the “View all Summer Sale deals” button, the createCampaignCookie Server Action is called. The user clicking on the button shows that they interacted with the page.

This Server Action can be defined in the src/app/actions.ts file:

Click to Copy
"use server"; import { cookies } from "next/headers"; export async function createCampaignCookie(value: string) { if (value === "") return; cookies().set({ name: "campaign", value: value, httpOnly: true, secure: true, path: "/", }); }

When a user clicks on the button, the Server Action creates a cookie in the user’s browser. You can then do a check for the cookie in a Server Component using the cookies().get() method to serve the user-customized content.

If you’re using the Next.js pages directory, use the cookies method of the NextResponse interface to create or read cookies. You can use this method in an API route or the getServerSideProps function.

Note that you should let your users know what types of cookies are used on your website for their privacy and to comply with regulations such as the General Data Privacy Regulation (GDPR) in the European Union.

  • Sentry BlogCommon Errors in Next.js and How to Resolve Them
  • Community SeriesDebug Next.js with Sentry
  • ResourcesJavaScript Frontend Error Monitoring 101
  • Syntax.fmListen to the Syntax Podcast
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.