Saturday, June 24, 2017

Req.headers.cookie is empty, even with cookies in request headers

Leave a Comment

With Express I have the following setup:

const express = requires("express"); const path = requires("path"); const bodyParser = requires("body-parser"); const cookieParser = requires("cookie-parser");  let server = express(); server.set("port", (process.env.PORT || 5000)); server.set("views",  path.join(__dirname, "/views")); server.set("view engine", "ejs"); server.use(cookieParser()); server.use(express.static(self.workingDirectory + "/public")); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: true })); server.use((req, res, next) => {     // if req.cookies exists and testcookie is undefined within req.cookies     if ( req.cookies && typeof req.cookies["testcookie"] === "undefined" ) {         console.log("Setting cookie! Testcookie was not found");         res.cookie("testcookie", "test", {             maxAge : ((((1000*60)*60)*24)*7), /* expire a week from today */             httpOnly: true /* document.cookie doesn't return this cookie */         });     }     next(); }); server.get("/", (req, res) => { res.render("pages/index"); }); server.listen(server.get("port"), () => { console.log("Server started!"); }); 

So when I visit / the cookie is set as appropriate, but on every visit after that it keeps getting set. Later when I run console.log(req.headers) through a new middleware it displays the following on every visit to /, even though the cookie should've been set:

The response headers have the cookie in them:

Am I doing something wrong here? I can't figure out what's wrong... Isn't cookie-parser meant to populate req.cookies with cookies from the req.headers.cookie property? Why is req.headers.cookie returning empty. req.headers.cookiealso returns empty if I comment out anything to do with cookie-parser.

2 Answers

Answers 1

I tried the above snippet and req.headers.cookie is not empty . I received the cookie value from req.header.

    const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser");  let server = express(); // server.set("port", (process.env.PORT || 5000)); // server.set("views",  path.join(__dirname, "/views")); // server.set("view engine", "ejs"); server.use(cookieParser()); // server.use(express.static(self.workingDirectory + "/public")); server.use(bodyParser.json()); server.use(bodyParser.urlencoded({ extended: true })); server.use((req, res, next) => {     // if req.cookies exists and testcookie is undefined within req.cookies     if ( req.cookies && typeof req.cookies["testcookie" ] === "undefined" ) {         console.log("Setting cookie! Testcookie was not found");         res.cookie("testcookie", "test", {             maxAge : ((((1000*60)*60)*24)*7), /* expire a week from today */             httpOnly: true /* document.cookie doesn't return this cookie */         });     }     next(); }); server.get("/", (req, res) => { console.log(req.headers);   res.send(`<h1> hello world </h1>`); }); server.listen(5000, () => { console.log("Server started!"); }); 

Answers 2

Doesnt seem to anything wrong with your code. Your code below (edited to remove view engine details) works. For reference its using the following npm package versions:

"dependencies": {     "body-parser": "^1.17.2",     "cookie-parser": "^1.4.3",     "express": "^4.15.3"   }  

Added an additional middleware (exampleMiddleWare) to highlight the cookie check on route.

const express = require("express"); const path = require("path"); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser");  let server = express();  server.set("port", (process.env.PORT || 5000));  server.use(cookieParser());  server.use(bodyParser.json()); server.use(bodyParser.urlencoded({extended: true}));  server.use((req, res, next) => {     // if req.cookies exists and testcookie is undefined within req.cookies     if (req.cookies && typeof req.cookies["testcookie"] === "undefined") {         console.log("Setting cookie! Testcookie was not found");         res.cookie("testcookie", "test", {             maxAge: ((((1000 * 60) * 60) * 24) * 7), /* expire a week from today */             httpOnly: true /* document.cookie doesn't return this cookie */         });     }     next(); });  const exampleMiddleWare = (req, res, next) => {     res.hasTestCookie = !!req.cookies.testcookie     next(); };  server.get("/", exampleMiddleWare, (req, res) => {     res.send(`<h1>Cookie Test</h1><h2>Cookie Found: ${res.hasTestCookie}</h2>`); });  server.listen(server.get("port"), () => {     console.log("Server started!"); }); 

If you can not get the above working then maybe sanity check within a different browser as your cookie settings can be overwritten or changed with browser options and plugins.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment