How to structure a Vue project  - Authentication

How to structure a Vue project  - Authentication

How to structure a Vue project - Authentication, For the past few years my primary focus has been on the software architecture and development of the backend services.

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:

  • Vue.js 2.5 and Vue-CLI
  • Vuex 3.0
  • Axios 0.18
  • Vue Router 3.0

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

Protected pages

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

Making API requests

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:

  • Vue.js 2.5 and Vue-CLI
  • Vuex 3.0
  • Axios 0.18
  • Vue Router 3.0

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.

Should I place it in Vuex store or Component?

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!

Extra: How to refresh expired access token?

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

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!

Collection of 15 Vue Input Component for Your Vue.js App

Collection of 15 Vue Input Component for Your Vue.js App

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

Vue input component gives you a baseline to create your own custom inputs. It consists of a prepend/append slot, messages, and a default slot. In this article I will share 15 Vue input components to you.

1. Maska
  • No dependencies
  • Small size (~2 Kb gziped)
  • Ability to define custom tokens
  • Supports repeat symbols and dynamic masks
  • Works on any input (custom or native)

Demo

Download


2. v-range-flyout

A vue component that wraps a input type=number with a customizable range slider flyout with 2-way binding.

Demo

Download


3. vue-tel-input

International Telephone Input with Vue.

Demo

Download


4. Restricted Input

Allow restricted character sets in input elements.

Features

  • Disallow arbitrary characters based on patterns
  • Maintains caret position
  • Format/Update on paste
  • Works in IE11+

Demo

Download


5. Vue Currency Input

The Vue Currency Input plugin allows an easy input of currency formatted numbers.

Demo

Download


6. vue-fields

Input components for vue.js.

Demo

Download


7. vue-material-input

Simple example of issue I am seeing with input labels.

Demo

Download


8. vue-tribute

A Vue.js wrapper for Zurb's Tribute library for native @mentions.

Demo

Download


9. vue-number-smarty

Number input with rich functionality for Vue.js.

Features

  • integer/float
  • signed/unsigned
  • step size
  • increment/decrement value by scrolling when focused
  • align variants
  • min and max boundaries
  • max length of integer part (only for float type)
  • max length of float part (only for float type)
  • max length of string
  • error state
  • readonly state
  • theme options

Demo

Download


10. Vue input mask

Super tiny input mask library for vue.js based on PureMask.js (~2kb) exposed as directive. No dependencies.

Demo

Download


11. vue-r-mask

mask directive for vue.js

  • Template similar to javascript regular expression. /\d{2}/
  • Directive useful for your own input or textarea.
  • Arbitrary number of digits in template /\d{1,10}/

Demo

Download


12. Vue IP

An ip address input with port and material design support.

Demo

Download


13. v-money Mask for Vue.js

Tiny input/directive mask for currency

Features

  • Lightweight (<2KB gzipped)
  • Dependency free
  • Mobile support
  • Component or Directive flavors
  • Accept copy/paste
  • Editable

Demo

Download


14. Vue Masked Input

Dead simple masked input component for Vue.js 2.X. Based on inputmask-core.

Demo

Download


15. VueJS input component

Mobile & Desktop friendly VueJS input component
Features used
CSS variables
Vue's transition-group
Flexbox

Demo


I hope you like them!