D
D
DaBags2021-03-08 20:50:29
Vue.js
DaBags, 2021-03-08 20:50:29

When to check the validity and lifetime of a vue.js token?

I study vue.js and there is a registration / authorization functionality for api. The back is located on another server and I would like to first check the token on the front (validity and lifespan) before sending the request, at least as much as possible. To decode the token I use jwt-decode

So far, only this comes to mind

const token = localStorage.getItem('token');
        if (token) {
            const decoded = jwt_decode(token);

            if (typeof decoded !== 'object') {
                // если маршрут требует авторизации, то отправляем на страницу авторизации
            } else {
                let shelfLife = decoded.exp * 1000, 
                    currentDate = new Date();

                if (shelfLife < currentDate) {
                    // делаем запрос на обновление токена
                }
            }
        }


And execute this code in the global navigation hooks router.beforeEach

Is this the right approach and how to do the token check in such cases? Or is it worth just in any case sending a request to the back and checking the token there already?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2021-03-09
@DaBags

Why create a mess for yourself out of the blue when you can wait for a response from the server and process its response? Moreover, you will have to do this check with EVERY request, otherwise it makes no sense at all. And the same check will be done by the server.
So why drag the logic of the back to the front?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question