skip to Main Content

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


  1. In development/http, use secure: false. Secure being true prevents cookies being set in http communications.

    I also recommend setting up a dotenv (.env) configuration for local development and then doing something like

    secure: process.env.INSECURE_COOKIES !== "true"

    and then in your envfile (usually .env) putting

    INSECURE_COOKIES=true

    Login or Signup to reply.
  2. When using httpOnly, on the frontend javascript cannot access to the cookie. Plus, it can only be send using https protocol.

    When using sameSite:"None", the secure attribute must be set to true.

    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 Chrome chrome://flags/
    • turn httpOnly:false, sameSite: "Strict" and secure:false if process.env.NODE_ENV !== "production" (make sure it is set to production when deploying to production)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search