How to properly check authentication with Vue.js (Vue router) and Django

I am trying to check if a user is authenticated on protected routes in vue-router. I have Django rest framework that sets sessionid on login.

I have seen people using vuex or local storage to store session information. But, If the token was forcibly expired on the server-side a user will be allowed to navigate since localStorage still says IsAuthenticated=true. In this case, is it the best choice to make a request to the Django backend such as fetch("url/auth/authenticated")?

Please consider adding routing guard on protected routes.

Vue Router permits you to do stuff before entering any route.

The following docs get you covered. Do remember that your API response is what rules you front end. So for checking if a sessionid is still valid, you can create an endpoint to do that and when it respond with an expired state, your frontend should unset everything related to the session in your vuex store and from the local storage, then redirect the user to the connexion page!

It depends on your specific use case and requirements.

Using Vuex or local storage to store session information is a common approach, but as you mentioned, if the token is forcibly expired on the server-side, the user will still be able to navigate as the client-side state is not updated.

Making a request to the backend to check if the user is authenticated before navigating to a protected route is a way to ensure that the user's authentication status is up-to-date. However, this approach can lead to a delay in navigating to the protected route, and it also requires an additional network request.

Another approach is to use JSON Web Tokens (JWT) for authentication. JWT's are self-contained tokens that include all the information needed to authenticate a user, and they can be checked on the client-side without the need for an additional network request. However, JWT's have a short expiration time and they need to be refreshed regularly.

In summary, the best choice depends on your specific use case and the trade-offs you are willing to make between security and performance.

Back to Top