DEV Community

Sowmo0509
Sowmo0509

Posted on

Setting Up A Cookie From NEXT.JS Back-end

Hello there, good people! I was literally stuck for a couple of hours on this issue and as a beginner, I am pretty sure most of us will be facing or already faced these kind of cookie setting troubles in NEXT.JS server-side.

To set a cookie, you just need one package, cookie. And remember, serious cookies should be sent from the server. In Express servers, it is pretty easy; just res.cookie() and you are ready to go. But, in NEXT.JS, you can not just use res.cookie() directly as far I am concerned. So, here's a solution instead:

import cookie from "cookie";

// token = your JWT signed token  
res.setHeader("Set-Cookie", cookie.serialize("token", token, COOKIE_OPTIONS));
Enter fullscreen mode Exit fullscreen mode
  1. "token" : the name of the token.
  2. token : jwt signed token, STRING, which will be stored inside the token.
  3. COOKIE_OPTIONS : this is my current cookie option:
const COOKIE_OPTIONS = {
    httpOnly: true,
    secure: process.env.NODE_END !== "development",
    sameSite: "strict",
    maxAge: 3600,
    path: "/",
  };
Enter fullscreen mode Exit fullscreen mode

This is how I stored my cookies.

To remove this cookie:

const COOKIE_OPTIONS = {
    httpOnly: true,
    secure: process.env.NODE_END !== "development",
    sameSite: "strict",
    maxAge: 0, //make sure this is 0
    path: "/",
  };
res.setHeader("Set-Cookie", cookie.serialize("token", "", COOKIE_OPTIONS));
Enter fullscreen mode Exit fullscreen mode

This is how the whole login and logout cookie process works. Thanks! Hope this will help someone like me!

Top comments (0)