Search code examples
javascriptreactjsnext.jscookiesnext.js13

Cookies Not Being Set in Production in Next.js App


I'm working on a Next.js application where I'm setting a cookie after a successful login. The cookie is supposed to store an authentication token. This works as expected in my local development environment, but when deployed to production, the cookie is not being set.

Here's the function I use to set the cookie:

import Cookies from 'js-cookie';

async function saveCookie(token) {
    Cookies.set('auth_token', token, {
        httpOnly: process.env.NODE_ENV !== 'development',
        expires: 60,
        secure: process.env.NODE_ENV !== 'development',
        sameSite: 'lax',
        path: '/',
    });
}

In production, the login functionality works, and the API returns a token as expected. However, the auth_token cookie does not appear in the browser's cookie storage.

Attached is a screenshot showing that the user is logged in (indicating the token is received), but the cookie is not visible in the browser's cookies.

enter image description here

I have deployed the frontend on Netlify with an environment variable NODE_ENV=production.

Why is the cookie not being set in the production environment, despite other parts of the application running as expected?


Solution

  • I believe you may need to set the expires time for one day

    1 Day = 24 Hrs = 246060 = 86400.

    and same site set the none and also set domain name then it works

    Cookies.set('auth_token', token, { domain: 'here name', expires: 1/86400, secure: true, sameSite: 'None', path: '/', });

    I hope this solution resolves your issue.