Unable to set a cookie with "sameSite: none" and "secure: true" attributes while redirecting with ExpressJs

294 Views Asked by At

I am facing an issue with setting a cookie while redirecting the users after authentication with Google OAuth 2.0. The backend server is using Node.js with Express.js, and the frontend is hosted on a different domain from the backend. Both the frontend and Nginx are using HTTPS, but the connection between Nginx and the server is over HTTP.

I am trying to set a cookie after successful Google OAuth 2.0 authentication and then redirect the user to the frontend domain using the res.redirect() method.

The code snippet to set the cookie looks like this:

res.cookie("cookie", cookieValue, {
    httpOnly: true,
    sameSite: "none",
    secure: true,
    maxAge: 3 * 24 * 60 * 60 * 1000,
});

However, the cookie is not being set in the browser. This issue only occurs when the user is redirected to the frontend domain. In the localhost environment, everything works as expected.

Backend Server Configuration:

app.set("trust proxy", 1);

app.use(cors({
    credentials: true,
    origin: "https://frontend.com",
}));

app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(session({
    secret: "session_secret",
    resave: false,
    saveUninitialized: false,
}));

Nginx Configuration:

location /api/ {
    proxy_pass http://ip.address:port;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
1

There are 1 best solutions below

0
ABHISHEK BHAT On

My front end was blocking cookies, resolved it with some configs.

Note: Added some nginx configs also

proxy_set_header Cookie $http_cookie;
proxy_set_header SameSite SameSite=None;
proxy_set_header Secure Secure;