How to manage cookies in VueJS

Vue Cookies [large]

The web has moved fast in the last few years. It’s one of the reasons why I switched from being an iOS developer to being a web developer. React was probably one of the earliest and most influential softwares products for lifting the web to the next level.

In case you tried to write websites before 2013, you probably used PHP or Java Servlets to create websites. They were clunky and moving fast was a pain in the butt. Opposed to the use of pure templates, new web frameworks try to use the concept of components. Components are reusable and encapsulated HTML entities to make the development on the web easier. This also makes collaborating on a common code base much easier by assigning task by components. As a result, conflicts can be reduced and introducing new team members to the code base is easy. This was one of the main reasons Facebook has built React. But, React wasn’t the only player on the field and VueJS emerged - a viable competitor to React.

One of the most common usage scenarios of any website is the sharing of state between a web server and a website visitor. May it be to enable logins or the tracking of events during an onboarding sequence that the visitor has triggered. It’s an essential part to any website except you only have a static site for your resume, for instance.

But how can we do that in VueJS? In case you didn’t know, here the logic between client and server is decoupled and you end up with two separate code bases essentially. If you haven’t used it yet, VueJS works by generating a single Javascript file which is responsible for rendering the website’s content. After the script has loaded and the user performs an action like clicking a button or switching a view, no new web request will be issued to the webserver if you use VueJS native routing framework by using the following syntax:

<router-link :to="{name: 'about-page'}">About</router-link>

Behind the scene VueJS will replace the syntax above with a standard anchor tag <a> but disables its default behavior for mouse clicks. Instead, a custom Javascript event is attached to every anchor element. There, a function waits to re-render the DOM in case a matching rule is found.

But, this is a problem, what happens if you want to design a website with a basic login mechanism. Either via a normal HTML form or via a custom logic by issuing a POST request to your web server. The website will be reloaded if you used a standard HTML form but your VueJS program won’t know whether your visitor is logged in or not. Also, reloading your website will purge your state in Vuex, which is used to handle application-wide state management in VueJS. Hence, this isn’t an option either. You either have to use URL parameters or Cookies. URL parameters are not the way to go because they make synchronizing the state with VueJS unnatural.

For my Japanese learning site which is hopefully soon the best app for learning Japanese on the web, I decided to use VueJS after Facebook decided to alter its licence for React causing a lot of havoc last year. Obviously, I had to come up with a way to handle state in a straightforward manner. Even my simple katakana converter will soon save state to a certain extent. It will able to store users’ recent words in case they want to resume from where they left off. The typical way is to use cookies for that.

The question is, how can you do that in a way that let’s you leverage the reactiveness of VueJS and synchronize the state with your server while not reloading your single page application constantly. Simple, with interceptors. These are available if you use the popular axios.js framework for web browsers and node.js. It is the request framework of choice for VueJS. Therefore you’ll already be using it if you followed their tutorials.

If you used the VueJS command line interface for initiating a new project or use any of the starter project on Github by Microsoft, you’ll either have a main.ts or a index.ts file where you want to add the code snippet from below.

import * as update from "./update";
import axios from "axios";

axios.interceptors.response.use((response) => {
  update.update_from_cookies();
  return response;
});

This code snippet will execute the code on line 5-6 every time you use axios to issue a GET, POST, PUT or DELETE request to any webserver. On line 5, my own logic for updating Vuex’s store based on the state of the cookies will be called. This results in having no redundant code in various parts of your VueJS application on state altering HTTP requests.

import Cookie from "js-cookie";

export function update_from_cookies() {
    let logged_in = Cookie.get("logged_in");
    if (logged_in && JSON.parse(logged_in)) {
        store.commit("logged_in", true);
    } else {
        store.commit("logged_in", false);
    }
}

In the helper function for synchronizing cookies with Vuex, you have to check for every cookie which is set and update the state with Vuex’s store instance by calling the corresponding commit functions as you can see above.

If you want to see the code in an example project, I took the freedom to create one. You can check out VueJS’s starter project generated with VueCLI and with the code above applied to it here. I hope this was of any help to you if you just wanted to start out using VueJS. If you liked this tutorial, I have another one where I explain how to create a sticky footer with flexbox.


The mind agrees.