Why is req.cookies undefined?
Asked Answered
L

9

23

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>
Loiseloiter answered 18/1, 2017 at 13:31 Comment(5)
Are there any errors in the browser console ? You seem to have some code in <script> tags and some outside. I guess it's juste a different place where you pasted from... also, is the cookie properly set in your browser ?Equi
@Equi Thx for coming to help ! Yes, the missing script tag for just a copy paste issue. How can I check if the cookie is properly set in my browser ?Loiseloiter
@Equi Added a screenshot to the question.Loiseloiter
@Equi Please add an answer so I can award you the bounty. I don't want to waste it. You put me in the right direction to find the answer.Loiseloiter
I did, thanks @Loiseloiter !Equi
E
8

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
                 });
            });
Equi answered 21/1, 2017 at 17:6 Comment(0)
J
28

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());
Jury answered 18/1, 2017 at 14:27 Comment(1)
Thanks literally forgot to import cookie parserEqualizer
G
17

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.

Glomeration answered 20/1, 2017 at 17:24 Comment(0)
E
8

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
                 });
            });
Equi answered 21/1, 2017 at 17:6 Comment(0)
L
2

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.

Loiseloiter answered 21/1, 2017 at 4:13 Comment(1)
I've worked on this issue for two days. Thanks for the question and the answer!Dylan
A
1

Did you enable cookie-parser middleware ? (https://www.npmjs.com/package/cookie-parser)

Astrid answered 18/1, 2017 at 13:47 Comment(0)
E
0

Try adding credentials: 'include' to your fetch call, like so:

fetch(`${process.env.SERVER_URL}/`, { 
method: "POST",
credentials: "include",
headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
 })
 .then(res => res.json()).then(data => console.log(data))

The reason it works when you manually access the address is because HTTP requests made by the browser send cookies in the header by default. Fetch doesn't.

Enlistment answered 4/7, 2023 at 10:9 Comment(0)
P
0

Follow other's comment but if you still face any problem, try to use your browser's developer tools (client-side) to check network queries. Check the request headers to ensure that whether the cookie is being sent with the request to '/your-route'. Confirm that the cookie is received successfully. Sometimes it can shows error for some reasons.

Pickpocket answered 8/5 at 23:49 Comment(0)
S
0

If you are working for local or remote website for example: localhost:3000 then you need to add domain enter image description here

Then you can add a cookie for example: locale=en enter image description here

Strasser answered 20/7 at 14:22 Comment(0)
T
-2

I am also stuck in this problem, there is a simple way to solve this problem, and that is to install cookie-parser, and then:

const express = require("express")
const app = express()
const cookie Parser  = require("cookie-parser")
app.use(cookie Parser ())

That will solve it. If you find the same error reoccurs, just wait for an hour, shutdown your pc or laptop, then after some time when you try to get cookies in backend from frontend it's possible.

Note: Don't try again and again due this error are also occur.

Threephase answered 17/1, 2023 at 8:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.