Express setCookie not working locally or in production

7 months agoa minute read

When we work locally we have to set the value of secure: false and sameSite: "strict" but when uploaded to a production environment we have to use sameSite: "none" and secure: true

so we can use this simple code to make it automatically do that

res.cookie(
    "token",
    tokenValue,
    {
        httpOnly: true,
        secure: process.env.NODE_ENV === "production" ? true: false,
        sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
    }
)
res.clearCookie(
    "token",
    {
        maxAge: 0,
        secure: process.env.NODE_ENV === "production" ? true: false,
        sameSite: process.env.NODE_ENV === "production" ? "none" : "strict",
    }
)

So when the the NODE_ENV is production we use values for production and in development we use values for that.

Write your comment

Login to comment

ShahriyarAlam

Copythight © All Rights Reserved.