Tutorial

Vue.js JWT Patterns

Published on February 19, 2018
author

Joshua Bemenderfer

Vue.js JWT Patterns

JWT’s or JSON Web Tokens are a popular method of storing verifiable session state safely on the client without the need for stateful servers. They’ve grown in popularity immensely lately along with the rise of “serverless” web applications. JWTs are a core part of your application’s state, but are both a token and a piece of parsable data. So how do we use them in both ways? Here are a couple patterns that can make working with JWTs in Vue.js a breeze.

Throughout this guide we’ll be pretending we have a API endpoint that responds with a JWT as a string at GET http://localhost/vuejs-jwt-example/auth?u=username&p=password. You’d want to replace this with your own implementation.

How to persist the JWT across sessions is left to you, just be aware of the dangers of storing sensitive data in localStorage!

Without Vuex

Probably the most important recommendation I would make is to never store a parsed version of the JWT. Having both a string and a parsed object stored separately is setting yourself up for a world of pain.

Instead, use Vue.js’ computed properties to create the object on-demand from the string whenever the string is updated.

With a basic Vue.js component, that might look like this:

<template>
  <div>
    <p>JWT: {{jwt}}</p>
    <p>User ID: {{jwtData.sub}}</p>
    <p>Issuer: {{jwtData.iss}}</p>
    <button @click.native="doSomethingWithJWT()">Do Something</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      jwt: ''
    }
  },

  computed: {
    // this.jwtData will update whenever this.jwt changes.
    jwtData() {
      // JWT's are two base64-encoded JSON objects and a trailing signature
      // joined by periods. The middle section is the data payload.
      if (this.jwt) return JSON.parse(atob(this.jwt.split('.')[1]));
      return {};
    }
  },

  methods: {
    async fetchJWT() {
      // Error handling and such omitted here for simplicity.
      const res = await fetch(`http://localhost/vuejs-jwt-example/auth?u=username&p=password`);
      this.jwt = await res.text();
    },

    async doSomethingWithJWT() {
      const res = await fetch(`http://localhost/vuejs-jwt-example/do-something`, {
        method: 'POST',
        headers: new Headers({
          Authorization: `Bearer: ${this.jwt}`
        })
      });
      // Do stuff with res here.
    }
  },

  mounted() {
    this.fetchJWT();
  }
}
</script>

With Vuex

If you’re using Vuex, you can use a similar pattern based on Vuex actions and getters.

Here’s a example user vuex module that allows you to fetch a JWT and access it in both string and object form.

export const UserModule = {
  state: {
    currentJWT: ''
  },

  getters: {
    jwt: state => state.currentJWT,
    jwtData: (state, getters) => state.currentJWT ? JSON.parse(atob(getters.jwt.split('.')[1])) : null,
    jwtSubject: (state, getters) => getters.jwtData ? getters.jwtData.sub : null,
    jwtIssuer: (state, getters) => getters.jwtData ? getters.jwtData.iss : null
  },

  mutations: {
    setJWT(state, jwt) {
      // When this updates, the getters and anything bound to them updates as well.
      state.currentJWT = jwt;
    }
  }

  actions: {
    async fetchJWT ({ commit }, { username, password }) {
      // Perform the HTTP request.
      const res = await fetch(`http://localhost/vuejs-jwt-example/auth?u=${username}&p=${password}`);
      // Calls the mutation defined to update the state's JWT.
      commit('setJWT', await res.text());
    },
  }
}

Which can be used in a component similar to the one we wrote above like so:

<template>
  <div>
    <p>JWT: {{jwt}}</p>
    <p>User ID: {{jwtSubject}}</p>
    <p>Issuer: {{jwtIssuer}}</p>
    <button @click.native="doSomethingWithJWT()">Do Something</button>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'jwt',
      'jwtSubject',
      'jwtIssuer'
    ])
  },

  methods: {
    ...mapActions([
      `fetchJWT`
    ]),

    // The implementation here doesn't change at all!
    async doSomethingWithJWT() {
      const res = await fetch(`http://localhost/vuejs-jwt-example/do-something`, {
        method: 'POST',
        headers: new Headers({
          Authorization: `Bearer: ${this.jwt}`
        })
      });
      // Do stuff with res here.
    }
  },

  mounted() {
    this.fetchJWT({
      // #Security...
      username: 'username',
      password: 'password'
    });
  }
}
</script>

The benefit of the approach shown here is that the JWT iself is only ever stored and updated in string form. (The form used for API requests and validation.) Vue.js’ computed properties allow us to transform that however we need without requiring any extra state synchronization.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Joshua Bemenderfer

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Maybe late for me reading this article, but I would like to ask, for example if the user refresh the page all data in the store object of Vuex is lost, what other approach can you suggest to recover de jwt token. Thanks in advance!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.