ReactHustle

How to Set Server-Side Cookie In Next JS

Jasser Mark Arioste

Jasser Mark Arioste

How to Set Server-Side Cookie In Next JS

Hello, hustlers! In this tutorial, you'll learn how to set server-side cookies in NextJS. We'll do them in middleware, getServerSideProps, and API routes.

Prerequisites #

To follow this tutorial, you should have at least NextJS v12.3.4.

Setting Cookies in middleware.ts #

Setting cookies in middleware is the easiest since NextJS already provides us with an awesome API. To set cookies in middleware we can us the NextResponse object:

// middleware.ts
import { NextRequest, NextResponse } from "next/server";
export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  //Setting cookies in response.
  //This will be sent back to the browser.
  res.cookies.set("my-cookie", "my-cookie-value", {
    path: "/",
    httpOnly: true,
  });

  // Setting cookies in the request.
  // This will be forwarded to api handler or getServerSideProps
  // depending on the route.
  req.cookies.set({
    name: "test",
    value: "test-cookie-value",
  });
  return res;
}
1234567891011121314151617181920

Setting Cookies in API handler #

To set cookies in an API handler, we'll install the cookie package to make it easier to write cookies. Since it is executed on the server-side, we don't have to worry about the package size.

yarn add cookie && yarn add -D @types/cookie
1

Now, let's set a cookie in /api/hello.ts using res.setHeader method:

// pages/api/hello.ts
import { serialize } from "cookie";
import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const cookie = serialize("hello-cookie", "api-hello-cookie-value", {
    httpOnly: true,
    path: "/",
  });
  res.setHeader("Set-Cookie", cookie);
  res.status(200).json({ message: "Successfully set cookie!" });
}
1234567891011

We use the serialize function to encode the cookie into a string. We use the Set-Cookie header so that the cookie will be sent to the user agent. Now, if you go to /api/hello and open the dev tools, you should see the hello-cookie cookie.

Setting Cookies in getServerSideProps #

Setting cookies in getServerSideProps is similar to API handler. We'll still use the serialize function like so:

import { serialize } from "cookie";
import { GetServerSideProps } from "next";
import React from "react";
const SsrPage = () => {
  return <div>SsrPage</div>;
};
export default SsrPage;
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
  const cookie = serialize("ssr-cookie", "ssr-cookie-value", {
    httpOnly: true,
    path: "/",
  });
  res.setHeader("Set-Cookie", cookie);
  return {
    props: {},
  };
};
1234567891011121314151617

That's it!

The full code can be accessed here: nextjs-set-cookies-tutorial

Conclusion #

We learned how to set cookies from the server-side in NextJS. The cookie package is a great tool for helping us write cookies.

If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.

Further Reading #

Improve your NextJS knowledge by reading my previous tutorials:

Credits: Image by congerdesign from Pixabay

Share this post!

Related Posts

Disclaimer

This content may contain links to products, software and services. Please assume all such links are affiliate links which may result in my earning commissions and fees.
As an Amazon Associate, I earn from qualifying purchases. This means that whenever you buy a product on Amazon from a link on our site, we receive a small percentage of its price at no extra cost to you. This helps us continue to provide valuable content and reviews to you. Thank you for your support!
Donate to ReactHustle