How to save user sessions with Vue.js?

Sometimes, we want to save user sessions with Vue.js.

In this article, we’ll look at how to save user sessions with Vue.js.

How to save user sessions with Vue.js?

To save user sessions with Vue.js, we can use the vue-session package.

To install it, we run

npm i vue-session

Then we register the plugin by writing

import VueSession from 'vue-session'

Vue.use(VueSession)

And then we can use it with

<script>
//...
export default {
  //...
  beforeCreate() {
    if (!this.$session.exists()) {
      this.$router.push("/");
    }
  },
  methods: {
    logout() {
      this.$session.destroy();
      this.$router.push("/");
    },
  },
  //...
};
</script>

to call this.$session.exists to check if the session is created.

And we call this.$session.destroy to destroy the session.

We can add an entry into the session with

this.$session.set('jwt', token)

where 'jwt' is the key and token is the value.

Conclusion

To save user sessions with Vue.js, we can use the vue-session package.