I’ve tried to stay away from front-end as long as possible since it’s the one area of software development where I feel mostly useless and unproductive.
So with the wish to sharpen my skills a bit I’ve decided to dig a bit into front-end development and see how it plays out. I’ve done some Angular quite a few years back so I thought I’d try the latest version but since Vue is growing in popularity and we’ve recently started using it at our company I’ve decided to give it a go. There are some quite long code snippets here, as I tried to structure this post more in a tutorial fashion — I hope you’ll still make it to the end :)
Generally when starting to work in a new framework or language I try to lookup as many best practices as possible as I prefer to start with a good structure that can be easily understood, maintained and upgraded in the future. In this post I will try to explain my thinking and combine all the knowledge I’ve obtained in the last few years with the latest and greatest web development practices.
Together we will build a simple project that handles authentication and prepare basic scaffolding to use when building the rest of the app.
We’ll be using:
Here is the end project structure that we’ll come up with when all is said and done. I assume that you’ve read through the Vue, Vuex and Vue Router documentation and that you understand the basics behind it — if you didn’t don’t panic, I’ll keep things simple, just don’t expect to learn everything from this post ;)
└── src
├── App.vue
├── assets
│ └── logo.png
├── components
│ └── HelloWorld.vue
├── main.js
├── router.js
├── services
│ ├── api.service.js
│ ├── storage.service.js
│ └── user.service.js
├── store
│ ├── auth.module.js
│ └── index.js
└── views
├── About.vue
├── Home.vue
└── LoginView.vue
First let’s protect some of the URLs to be accessible only to logged in users. To do this we need to edit router.js. I’ve taken the approach where all the pages are private except the ones we mark as public directly as I believe it’s better to set the visibility by default to private and expose the routes you want accessible to public by explicitly doing so.
In the code below we’re using the meta functionality of the Vue Router — you can read about it here. We’ll also be nice to our users and redirect them to the page they tried to access after the login. For the login view we kinda want it to be accessibly only when a user is not logged in so we’ve added another flag in the meta field named onlyWhenLoggedOut.
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import LoginView from './views/LoginView.vue'
import { TokenService } from './services/storage.service'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/login',
name: 'login',
component: LoginView,
meta: {
public: true, // Allow access to even if not logged in
onlyWhenLoggedOut: true
}
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
},
]
})
router.beforeEach((to, from, next) => {
const isPublic = to.matched.some(record => record.meta.public)
const onlyWhenLoggedOut = to.matched.some(record => record.meta.onlyWhenLoggedOut)
const loggedIn = !!TokenService.getToken();
if (!isPublic && !loggedIn) {
return next({
path:'/login',
query: {redirect: to.fullPath} // Store the full path to redirect the user to after login
});
}
// Do not allow user to visit login page or register page if they are logged in
if (loggedIn && onlyWhenLoggedOut) {
return next('/')
}
next();
})
export default router;
router.js
You’ll notice that we’re importing a TokenService which returns a token. The TokenService lives inside services/storage.service.js and all it does is encapsulate the logic that handles the storage and retrieval of the access token to and from localStorage.
This way we can safely migrate from local storage to cookies without having to worry that we’ll break some other service or component that accesses the local storage directly. I believe this is a good practice to follow in order to avoid future headaches. The code in the storage.service.js looks like this:
const TOKEN_KEY = 'access_token'
const REFRESH_TOKEN_KEY = 'refresh_token'
/**
* Manage the how Access Tokens are being stored and retreived from storage.
*
* Current implementation stores to localStorage. Local Storage should always be
* accessed through this instace.
**/
const TokenService = {
getToken() {
return localStorage.getItem(TOKEN_KEY)
},
saveToken(accessToken) {
localStorage.setItem(TOKEN_KEY, accessToken)
},
removeToken() {
localStorage.removeItem(TOKEN_KEY)
},
getRefreshToken() {
return localStorage.getItem(REFRESH_TOKEN_KEY)
},
saveRefreshToken(refreshToken) {
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
},
removeRefreshToken() {
localStorage.removeItem(REFRESH_TOKEN_KEY)
}
}
export { TokenService }
storage.service.js
We can use the same logic as we did in TokenService when it comes to API interaction. Make a base service which will do all the interaction with the network so we can easily change or upgrade stuff in the future. This is exactly what we’re trying to achieve with the api.service.js— encapsulate the Axios library so that when inevitably a new thing comes along we can return to this single service and upgrade it without having to refactor the whole application. Any other service that needs to interact with API will simply import the ApiService and issue requests via the helper methods we’ve implemented.
import axios from 'axios'
import { TokenService } from '../services/storage.service'
const ApiService = {
init(baseURL) {
axios.defaults.baseURL = baseURL;
},
setHeader() {
axios.defaults.headers.common["Authorization"] = `Bearer ${TokenService.getToken()}`
},
removeHeader() {
axios.defaults.headers.common = {}
},
get(resource) {
return axios.get(resource)
},
post(resource, data) {
return axios.post(resource, data)
},
put(resource, data) {
return axios.put(resource, data)
},
delete(resource) {
return axios.delete(resource)
},
/**
* Perform a custom Axios request.
*
* data is an object containing the following properties:
* - method
* - url
* - data ... request payload
* - auth (optional)
* - username
* - password
**/
customRequest(data) {
return axios(data)
}
}
export default ApiService
api.service.js
You might have noticed that there is an init and setHeader function in there. We will init the ApiServiceinside the main.js to make sure that we set the header if the user refreshes the page and also set the baseURL property.
To dynamically change the URL in development, staging and production environment I’m using the Vue CLI Environment Variables.
Inside your main.js file you’d place appropriate imports and then following lines:
rawmain.js
// Set the base URL of the API
ApiService.init(process.env.VUE_APP_ROOT_API)
// If token exists set header
if (TokenService.getToken()) {
ApiService.setHeader()
}
Okay, so by now we know how to redirect the user to a login page and we’ve done some basic boilerplate code that should help us keep a clean and maintainable project. Let’s start working on the user.service.js so we can actually make a request and see how to use our ApiService we just made.
import ApiService from './api.service'
import { TokenService } from './storage.service'
class AuthenticationError extends Error {
constructor(errorCode, message) {
super(message)
this.name = this.constructor.name
this.message = message
this.errorCode = errorCode
}
}
const UserService = {
/**
* Login the user and store the access token to TokenService.
*
* @returns access_token
* @throws AuthenticationError
**/
login: async function(email, password) {
const requestData = {
method: 'post',
url: "/o/token/",
data: {
grant_type: 'password',
username: email,
password: password
},
auth: {
username: process.env.VUE_APP_CLIENT_ID,
password: process.env.VUE_APP_CLIENT_SECRET
}
}
try {
const response = await ApiService.customRequest(requestData)
TokenService.saveToken(response.data.access_token)
TokenService.saveRefreshToken(response.data.refresh_token)
ApiService.setHeader()
// NOTE: We haven't covered this yet in our ApiService
// but don't worry about this just yet - I'll come back to it later
ApiService.mount401Interceptor();
return response.data.access_token
} catch (error) {
throw new AuthenticationError(error.response.status, error.response.data.detail)
}
},
/**
* Refresh the access token.
**/
refreshToken: async function() {
const refreshToken = TokenService.getRefreshToken()
const requestData = {
method: 'post',
url: "/o/token/",
data: {
grant_type: 'refresh_token',
refresh_token: refreshToken
},
auth: {
username: process.env.VUE_APP_CLIENT_ID,
password: process.env.VUE_APP_CLIENT_SECRET
}
}
try {
const response = await ApiService.customRequest(requestData)
TokenService.saveToken(response.data.access_token)
TokenService.saveRefreshToken(response.data.refresh_token)
// Update the header in ApiService
ApiService.setHeader()
return response.data.access_token
} catch (error) {
throw new AuthenticationError(error.response.status, error.response.data.detail)
}
},
/**
* Logout the current user by removing the token from storage.
*
* Will also remove `Authorization Bearer <token>` header from future requests.
**/
logout() {
// Remove the token and remove Authorization header from Api Service as well
TokenService.removeToken()
TokenService.removeRefreshToken()
ApiService.removeHeader()
// NOTE: Again, we'll cover the 401 Interceptor a bit later.
ApiService.unmount401Interceptor()
}
}
export default UserService
export { UserService, AuthenticationError }
user.service.js
We’re implementing a UserService which has 3 methods:
If you’ve paid attention you’ll notice that there is a mysterious 401 interceptor logic there — we’ll cover that in a moment. It’s there just so I don’t have to include another code snippet to show you where to place it.
It seems to be a good practice to put as much of your logic into the Vuex store. Primarily this is good because you can reuse the state and business logic in different components.
For example let’s say that your app allows users to login or register in multiple places — on a dedicated login/register page or, in case of a online shop, when they checkout their basket via a popup. You would probably use a different Vue component for that UI element. By placing your state and logic in the Vuex store you would be able to reuse the state and logic and simply make a few short import statements in your Component like this:
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "login",
data() {
return {
email: "",
password: "",
};
},
computed: {
...mapGetters('auth', [
'authenticating',
'authenticationError',
'authenticationErrorCode'
])
},
methods: {
...mapActions('auth', [
'login'
]),
handleSubmit() {
// Perform a simple validation that email and password have been typed in
if (this.email != '' && this.password != '') {
this.login({email: this.email, password: this.password})
this.password = ""
}
}
}
};
</script>
LoginView.html
In your Vue Component you would import logic from the Vuex Store and map state or getters to your computed values and actions to your methods. You can read a bit more about mapping here.
So how does our Vuex store look like for the user.service.js?
import { UserService, AuthenticationError } from '../services/user.service'
import { TokenService } from '../services/storage.service'
import router from '../router'
const state = {
authenticating: false,
accessToken: TokenService.getToken(),
authenticationErrorCode: 0,
authenticationError: ''
}
const getters = {
loggedIn: (state) => {
return state.accessToken ? true : false
},
authenticationErrorCode: (state) => {
return state.authenticationErrorCode
},
authenticationError: (state) => {
return state.authenticationError
},
authenticating: (state) => {
return state.authenticating
}
}
const actions = {
async login({ commit }, {email, password}) {
commit('loginRequest');
try {
const token = await UserService.login(email, password);
commit('loginSuccess', token)
// Redirect the user to the page he first tried to visit or to the home view
router.push(router.history.current.query.redirect || '/');
return true
} catch (e) {
if (e instanceof AuthenticationError) {
commit('loginError', {errorCode: e.errorCode, errorMessage: e.message})
}
return false
}
},
logout({ commit }) {
UserService.logout()
commit('logoutSuccess')
router.push('/login')
}
}
const mutations = {
loginRequest(state) {
state.authenticating = true;
state.authenticationError = ''
state.authenticationErrorCode = 0
},
loginSuccess(state, accessToken) {
state.accessToken = accessToken
state.authenticating = false;
},
loginError(state, {errorCode, errorMessage}) {
state.authenticating = false
state.authenticationErrorCode = errorCode
state.authenticationError = errorMessage
},
logoutSuccess(state) {
state.accessToken = ''
}
}
export const auth = {
namespaced: true,
state,
getters,
actions,
mutations
}
auth.module.js
This pretty much covers everything that you need to setup your project in a way that should hopefully help you keep things clean and maintainable.
Fetching more data from API should be easy now — simply make a new .service.js inside services, write helper methods and access API via the ApiService we made. To display this data make a Vuex Store and store the API responses in the state — use it in your Component via the mapState and mapActions. This way you’ll be able to reuse the logic in the future should you need to display or manipulate the the same data in a different component.
While I’m not a Vue expert (yet) I do like to think I know a thing or two about software architecture and I hope that this post contains some useful ideas and concepts that you can use in your next project!
What’s a bit harder and skipped by so many tutorials when it comes to authentication is handling token refresh or 401 errors. There are some use-cases where it’s good to simply logout the user when a 401 error happens, but let’s see how you can refresh the access token without interrupting the user experience. So here is the 401 Interceptor we’ve had in the above code samples mentioned already.
In our ApiService we’ll add the following code to mount the Axios response interceptor.
...
import { store } from '../store'
const ApiService = {
// Stores the 401 interceptor position so that it can be later ejected when needed
_401interceptor: null,
...
mount401Interceptor() {
this._401interceptor = axios.interceptors.response.use(
(response) => {
return response
},
async (error) => {
if (error.request.status == 401) {
if (error.config.url.includes('/o/token/')) {
// Refresh token has failed. Logout the user
store.dispatch('auth/logout')
throw error
} else {
// Refresh the access token
try{
await store.dispatch('auth/refreshToken')
// Retry the original request
return this.customRequest({
method: error.config.method,
url: error.config.url,
data: error.config.data
})
} catch (e) {
// Refresh has failed - reject the original request
throw error
}
}
}
// If error was not 401 just reject as is
throw error
}
)
},
unmount401Interceptor() {
// Eject the interceptor
axios.interceptors.response.eject(this._401interceptor)
}
}
api.service.js
What the code above does is intercept every API response and check if the status of the response is 401. If it is, we’re checking if 401 occurred on the token refresh call itself (we don’t want to be caught in the loop of refreshing token forever!). The code then refreshes the token and retries the request that has failed and returns the response back to the caller.
We’re dispatching a call to the Vuex store here to perform the token refresh. The code we need to add to our auth.module.js is:
const state = {
...
refreshTokenPromise: null // Holds the promise of the refresh token
}
const actions = {
...
refreshToken({ commit, state }) {
// If this is the first time the refreshToken has been called, make a request
// otherwise return the same promise to the caller
if(!state.refreshTokenPromise) {
const p = UserService.refreshToken()
commit('refreshTokenPromise', p)
// Wait for the UserService.refreshToken() to resolve. On success set the token and clear promise
// Clear the promise on error as well.
p.then(
response => {
commit('refreshTokenPromise', null)
commit('loginSuccess', response)
},
error => {
commit('refreshTokenPromise', null)
}
)
}
return state.refreshTokenPromise
}
}
const mutations = {
...
refreshTokenPromise(state, promise) {
state.refreshTokenPromise = promise
}
}
auth.module.js
You app will probably perform several API requests to obtain the data it needs to display. Should the access token expire all of the requests will fail and therefore trigger the token refresh inside the 401 interceptor. That would in term refresh the token for each request and that is not a good thing.
There are solutions out there that queue the requests when 401 happens and process them in a queue, but the code above, at least to me, provides a more elegant solution. By saving the refresh token promise and returning the same promise to every refresh token request we’re making sure that the token gets refreshed only once.
You’ll also need to mount the 401 interceptor in your main.js as well right after you set the request header.
Recommended Courses:
☞ Vuejs 2 + Vuex con TypeScript Nivel PRO
☞ Curso de Vuejs 2, Cognito y GraphQL
☞ Learn VueJS from Scratch: The Complete 1 Hour Crash Course!
☞ SSR con Vuejs, Vuex y Quasar Framework
☞ Curso Avanzado de Vuejs 2, Vuex y AdonisJs 4
#vue-js