shahriyar.dev
Back to blog
cookie-securityNODE_ENVsecure-cookiessameSiteexpress-cookiesenvironment-config

Automate Secure Cookie Handling Across Environments Using NODE_ENV

·2 min read

Handling cookies securely is a common pain point when moving between local development and production environments. The issue is that the secure and sameSite attributes of cookies need different values depending on where the application is running. In development over localhost, you typically set secure: false and sameSite: "strict", but in production over HTTPS, you need secure: true and sameSite: "none". Manually switching these values is error-prone and easy to forget.

The good news is that you can automate this switch with a single environment variable check, using process.env.NODE_ENV. This approach keeps your cookie configuration consistent and eliminates manual errors when deploying.

The key insight is to use a ternary expression that checks whether the application is running in production mode. When NODE_ENV equals "production", the cookie will use secure transmission and a sameSite value of "none", which works with cross-origin requests (common in modern web apps served over HTTPS). In any other environment (like development), it falls back to secure: false and sameSite: "strict", which is appropriate for local localhost setups.

Here is a practical code example for setting a cookie with this conditional logic:

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

When clearing a cookie, it is equally important to match the same secure and sameSite attributes. Otherwise, the browser may not properly delete the cookie. Use the same conditional logic here:

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

Why This Works

  • When NODE_ENV is set to "production", the cookie uses secure: true and sameSite: "none" — the correct combination for HTTPS environments with cross-origin requests.
  • In any other environment (like local development), it defaults to secure: false and sameSite: "strict", which works well over HTTP on localhost.

This pattern ensures that your cookie configuration automatically adapts without requiring manual changes during deployment. It is a simple, reliable way to keep your authentication cookies secure across different environments.

Comments