Search code examples
javascriptnode.jscookiesfirebasefirebase-authentication

Why is req.cookies undefined?


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>

Solution

  • 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
                     });
                });