Search code examples
javascriptnext.jscookiessubdomain

Set a cookie from subdomain to all subdomains


I'm working on a NextJS project where I have multiple apps on separate subdomains. My goal is to login in one app and automatically signed in at every other. We're using nookies as cookie handler, creating a cookie with a JWT token payload received from an API. I thought if I set the cookie domain manually then it's going to set the cookie on the main domain but it did not happen.

Here's what I've tried:

setCookie(
    null,
    "token",
    `JWT ${data.tokenAuth.token}`,
    {
        maxAge: 29 * 24 * 60 * 60,
        path: "/",
        domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN,
    }
);

I've set the NEXT_PUBLIC_COOKIE_DOMAIN as "example.com" and ".example.com", neither of them worked, my cookie was always set to the current subdomain. I also got the idea to put the login page under "example.com/login" to set the cookie on the main domain so I can access it everywhere, but I wonder if there's a solution to avoid it. I've already read about RFC 6265, from which I assume it's only possible from the main domain, yet the tracking we're using somehow can assign ".example.com" for it's cookie. What am I missing? Thanks for replies in advance.


Solution

  • To ensure cookies are shared across subdomains, set the domain attribute with a leading dot (e.g., ".example.com"). Avoid using SameSite: Strict for cross-site requests; instead, consider None with caution. Secure cookies are vital for HTTPS sites. Set the path attribute to "/" for domain-wide access. Verify the environment variable NEXT_PUBLIC_COOKIE_DOMAIN is correctly configured. Test your setup using browser tools to confirm the cookie's correct domain and attributes. These steps are crucial for effective cross-subdomain cookie sharing.

    Here's an example of how you might set the cookie using nookies:

    import { setCookie } from "nookies";
    
    // Set cookie with domain and other attributes
    setCookie(null, "token", `JWT ${data.tokenAuth.token}`, {
      maxAge: 29 * 24 * 60 * 60, // 29 days
      path: "/",
      domain: process.env.NEXT_PUBLIC_COOKIE_DOMAIN, // Should be ".example.com"
      secure: true, // Set to true if served over HTTPS
      sameSite: "None", // If necessary for your use case
    });