Set a http only cookie next API

Viewed 224

I'm trying to set a cookie using my nextjs api.

I tried to do "res.cookie" (based off expressJS), but res.cookie is apparently undefined in my API. res itself is not undefined, just the cookie property is undefined.

Then i tried the following code:

 import { serialize } from "cookie";
 res.setHeader(
            "Set-Cookie",
            serialize("jwt", `${response.data.access_token}`, {
                maxAge: 5000,
                expires: new Date("01 12 2021"),
                secure: true,
                httpOnly: true,
                sameSite: "lax",
            })
        );

        res.send("done"); 

This is also not working, It is not setting the cookie on my frontend.

2 Answers

If you want to use API in Next.js you must create a file in this path first:

./pages/api/file.js

Then you must add your all api codes in this async function and add res,req to it. Dont forget to import your libs before the function:

import { serialize } from "cookie";

export default async (req, res) => {
    res.setHeader(
        "Set-Cookie",
        serialize("jwt", `${response.data.access_token}`, {
            maxAge: 5000,
            expires: new Date("01 12 2021"),
            secure: true,
            httpOnly: true,
            sameSite: "lax",
            path: '/thePath',
            domain: 'yourdomain.com'
        })
    );

    res.send("done");
}

What I did to make this work is add a path to my options. Also had to change the expiration date to a valid date that is not in the past.

import { serialize } from "cookie";
     res.setHeader(
                "Set-Cookie",
                serialize("jwt", `${response.data.access_token}`, {
                    maxAge: 5000,
                    expires: new Date("01 12 2022"),
                    secure: true,
                    httpOnly: true,
                    sameSite: "lax",
                    path : '/'
                })
            );

        res.send("done"); 
Related