Home > database >  Cookie is not included in request header / Server side cannot read req.cookies
Cookie is not included in request header / Server side cannot read req.cookies

Time:12-31

I am learning and applying authentication for my blog website!

I am using express-session to handle logins. Cookie on the browser & server sessions works fine.

Cookies

However, I am having trouble retrieving cookies on the server-side express app. I tried the following:

  • With cookie-parser, req.cookies & req.signedCookies both returns [Object: null prototype].
  • Setting CORS
  • req.cookie & req.header.cookie returns undefined
  • I can see a "Cookie" header from my connection in the browser network tab.

My code / settings are as follows:

function auth (req, res, next) {
  // Problem: Cannot read browser cookie of HTTP requests.
  console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
  next();
}

router.get('/', auth, async (req, res) => { // ... }

Middlewares

app.use(cors({
  origin: ['http://localhost:3000'],
  credentials: true
}));
app.use(cookieParser())  // Also tried with secret option.
app.use(session({
  secret: 'top-secret',
  resave: true,
  rolling: true,
  saveUninitialized: false,
  store: store, // this is working
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 14,
    httpOnly: true,
    secure: process.env.NODE_ENV !== 'Development',
    sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
  }
}))

Thank you in advance :)

Edit 1: My fetch code: fetch code

CodePudding user response:

If your using http only you should consider 2 things:

Step1 while request in client side: you should send request like this:

        const req = await fetch("http://localhost:7000/api/auth/login", {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
    });
    const data = await req.json();

step 2 in express:

const allowedOrigins = ["http://localhost:8000"];
    const corsOptions = {
    origin: function (origin, callback) {
   if (allowedOrigins.indexOf(origin) !== -1) {
  callback(null, true);
    } else {
     var msg =
    "The CORS policy for this site does not "  
    "allow access from the specified Origin.";
     callback(new Error(msg), false);
   }
 },
optionsSuccessStatus: 200,
 credentials: true,
 };
app.use(cors(corsOptions));

now you can get coockies in express by using req.cookies.nameOfCookiesWhichYouSendThroughCoockieParser

  • Related