0

I'm trying to make it so that some pages only render whenever an user is logged in. However, I can't seem to find any documentation on how to retrieve cookies using vue.js. My project is being made with the mevn stack. And I saved the user cookie with:

        res.cookie('token', token, {
            maxAge: 24 * 60 * 60 * 1000,
            httpOnly: true
        });

The problem I'm facing now is retrieving this cookie, so that I can verify wether the user is logged in. I can't find anything on how to do this, so I'm asking it here.

/pages/crash.vue

data() {
        return {
            foo: false,
        };
    },
    mounted() {
        // Get cookie
        // If cookie is valid 
        // Set this.foo to true
        if (this.foo) {
            ...
        } else {
            window.location.href = '/login'
        }
    },
root
  • 21
  • 5
  • Testing whether a user is logged in must be done on the _server_, not on the _client_. And since the cookie is [httpOnly](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#httponly), you cannot access it on the client anyway. – Heiko Theißen May 25 '22 at 16:13
  • You have to use javascript. Refer here: https://stackoverflow.com/questions/10730362/get-cookie-by-name or here: https://stackoverflow.com/questions/5639346/what-is-the-shortest-function-for-reading-a-cookie-by-name-in-javascript – kuntervert May 25 '22 at 17:35
  • *retrieve cookies using vue.js* - vue.js is irrelevant - `document.cookie` is where all the cookies live, but not all of them – Bravo May 26 '22 at 01:49
  • @HeikoTheißen - how do you know the cookie is httpOnly? Nothing in the question suggests it is – Bravo May 26 '22 at 01:50
  • The first code snippet contains `httpOnly: true`. – Heiko Theißen May 27 '22 at 08:13

0 Answers0