Why is req.cookies undefined?
Solution 1
Apparently, your code is correct on the server. Hence, the cookie must not be set correctly on the client.
Copy/pasting the solution you found about disabling the secure cookie as you not using SSL:
const setAppCookie = () => firebase.auth().currentUser &&
firebase.auth().currentUser.getToken().then(token => {
Cookies.set('token', token, {
domain: window.location.hostname,
expire: 1 / 24, // One hour
path: '/',
secure: false // <-- false here when served over HTTP
});
});
Solution 2
I think you should paste some more server side code.
You need to use express.cookieParser() before app.router; middleware is run in order, meaning it's never even reaching cookieParser() before your route is executed.
Solution 3
In addition to requiring cookie-parser you should also configure your express app to use it:
var express = require('express');
var app = express();
var cookies = require("cookie-parser");
app.use(cookies());
Solution 4
I found the issue !
My cookie is not served over https (yet).
const setAppCookie = () => firebase.auth().currentUser &&
firebase.auth().currentUser.getToken().then(token => {
Cookies.set('token', token, {
domain: window.location.hostname,
expire: 1 / 24, // One hour
path: '/',
secure: true // If served over HTTPS
});
});
secure
needed to be set to false
.
Solution 5
Did you enable cookie-parser middleware ? (https://www.npmjs.com/package/cookie-parser)
Coder1000
Updated on January 22, 2020Comments
-
Coder1000 over 4 years
SITUATION:
I am trying to check if my user is authenticated when he makes a request to the server.
I googled a bit and found this:
How to show different page if user is logged in via firebase
So here's my try at implementing this solution using this library:
https://github.com/js-cookie/js-cookie/blob/latest/src/js.cookie.js
CODE:
server-side
var cookies = require("cookie-parser"); router.get("/", function(req, res, next){ const { token } = req.cookies; console.log('Verifying token', token); });
client-side
<script src="/public/js/cookieScript.js"> </script> <a href="/upload" class = "authIn uploadButton btn btn-success pull-right">UPLOAD</a> <script> const setAppCookie = () => firebase.auth().currentUser && firebase.auth().currentUser.getToken().then(token => { Cookies.set('token', token, { domain: window.location.hostname, expire: 1 / 24, // One hour path: '/', secure: true // If served over HTTPS }); }); </script>
-
firemaples over 4 yearsI've worked on this issue for two days. Thanks for the question and the answer!