JSON Web Tokens (JWT) are widely used for stateless authentication in web applications. In this article, we’ll see how to properly manage them in a Vue.js application, covering login, saving the token, sending it in requests, and logout.
1. Login and Receiving the JWT
After the user submits their credentials, the backend returns a JWT. This token must be saved for use in subsequent requests.
// Example of login call with Axios
axios.post('/api/login', {
username: 'user',
password: 'password'
})
.then(response => {
const token = response.data.token;
localStorage.setItem('jwt', token);
})
.catch(error => {
console.error('Login error:', error);
});
2. Setting the Token in Requests
Every authenticated request to the server must include the JWT in the Authorization
header.
// Global Axios configuration
axios.interceptors.request.use(config => {
const token = localStorage.getItem('jwt');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
3. Decoding the Token (Optional)
You can decode the token to read the data it contains, such as the user ID or role.
import jwtDecode from 'jwt-decode';
const token = localStorage.getItem('jwt');
if (token) {
const decoded = jwtDecode(token);
console.log('Logged-in user:', decoded);
}
4. Logout
To log the user out, simply remove the token from localStorage.
localStorage.removeItem('jwt');
5. Protecting Routes
You can use Vue Router navigation guards to block access to protected routes if the user does not have a valid token.
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('jwt');
if (to.meta.requiresAuth && !token) {
next('/login');
} else {
next();
}
});
Conclusion
Managing JWTs in Vue.js requires care but follows a simple pattern: login, token storage, usage in requests, optional decoding, and logout. It’s also important to handle token expiration and invalid tokens to ensure application security.