My cookies is being passed from the backend to the frontend and its also available at the Set-Cookie in the headers tab on the console, but with that, the cookies is not appearing at the frontend in the application tab, which logs me out on every reload.
This is My code at the backend: in My App.js
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser")
const bodyParser = require("body-parser")
const cloudinary = require("cloudinary")
const fileupload = require("express-fileupload");
const cors = require('cors')
const errorMiddleWares = require("./middleWares/errors")
// app.use(cors({ origin: "http://localhost:3000", credentials: true }));
const corsOptions = {
origin: true,
credentials: true,
};
app.use(cors(corsOptions));
and in my sendToken module for the cookies:
const sendToken = (user, statusCode, res) => {
// the user will be the userschema attached in the authusercontrolllers, also the status code too, but the res is from here
//create jwt token
const token = user.getJwtToken();
//to store jwt token in the cookie, we prepare options
const options = {
expires: new Date(
Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
),
httpOnly: true,
sameSite:"None",
secure:true
}
res.setHeader('Set-Cookie', `token=${token}`);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.status(statusCode).cookie("token", token, options).json({
success: true,
token,
user
})
};
2
Answers
In development/http, use
secure: false
. Secure beingtrue
prevents cookies being set in http communications.I also recommend setting up a
dotenv
(.env
) configuration for local development and then doing something likesecure: process.env.INSECURE_COOKIES !== "true"
and then in your envfile (usually
.env
) puttingINSECURE_COOKIES=true
When using
httpOnly
, on the frontend javascript cannot access to the cookie. Plus, it can only be send usinghttps
protocol.When using
sameSite:"None"
, thesecure
attribute must be set totrue
.See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
Those attributes are great for production usage, but on development you must change you approch either by using:
https
for localhost, need to generate some insecure key (do not commit them) and allow insecure localhost on Google Chromechrome://flags/
httpOnly:false
,sameSite: "Strict"
andsecure:false
ifprocess.env.NODE_ENV !== "production"
(make sure it is set toproduction
when deploying to production)