What steps can I take to optimize this Vue Js code without relying on local storage?

I'm working on implementing authentication for a Vue.js and Auth0 application. Currently, I have a code snippet that uses local storage to store and retrieve values like `expiresAt`, `idToken`, `accessToken`, and `user`. How can I refactor this code to directly access these values without relying on local storage?


        // Code snippet for handling authentication in Vue.js with Auth0

        import auth0 from 'auth0-js'
        import Vue from 'vue'

        let webAuth = new auth0.WebAuth({
            domain: 'your_auth0_domain',
            clientID: 'your_auth0_client',
            redirectUri: 'http://localhost:8080/callback',
            audience: 'https://' + 'your_auth0_domain' + '/api/v2/',
            responseType: 'token id_token',
            scope: 'openid profile' // define the scopes you want to use
        })

        let auth = new Vue({
            computed: {
                token: {
                    get: function () {
                        return localStorage.getItem('id_token')
                    },
                    set: function (id_token) {
                        localStorage.setItem('id_token', id_token)
                    }
                },
                accessToken: {
                    get: function () {
                        return localStorage.getItem('access_token')
                    },
                    set: function (accessToken) {
                        localStorage.setItem('access_token', accessToken)
                    }
                },
                expiresAt: {
                    get: function () {
                        return localStorage.getItem('expires_at')
                    },
                    set: function (expiresIn) {
                        let expiresAt = JSON.stringify(expiresIn * 1000 + new Date().getTime())
                        localStorage.setItem('expires_at', expiresAt)
                    }
                },
                user: {
                    get: function () {
                        return JSON.parse(localStorage.getItem('user'))
                    },
                    set: function (user) {
                        localStorage.setItem('user', JSON.stringify(user))
                    }
                }
            },
            methods: {
                login() {
                    webAuth.authorize()
                },
                logout() {
                    return new Promise((resolve, reject) => {
                        localStorage.removeItem('access_token')
                        localStorage.removeItem('id_token')
                        localStorage.removeItem('expires_at')
                        localStorage.removeItem('user')
                        webAuth.authorize()
                    })
                },
                isAuthenticated() {
                    return new Date().getTime() < this.expiresAt
                },
                handleAuthentication() {
                    return new Promise((resolve, reject) => {
                        webAuth.parseHash((err, authResult) => {
                            if (authResult && authResult.accessToken && authResult.idToken) {
                                this.expiresAt = authResult.expiresIn
                                this.accessToken = authResult.accessToken
                                this.token = authResult.idToken
                                this.user = authResult.idTokenPayload
                                resolve()
                            } else if (err) {
                                this.logout()
                                reject(err)
                            }
                        })
                    })
                }
            }
        })

        export default {
            install: function (Vue) {
                Vue.prototype.$auth = auth
            }
        }
    

Answer №1

Make use of vuex store

After retrieving the token from the endpoint, save it to local storage:

api_call_here
.then(response => {
  localStorage.setItem('token', response.body.token)
})

Your vuex store configuration should reflect this structure:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    isLogged: !!localStorage.getItem('token')
    token: localStorage.getItem('token') || null
}

This approach enables you to easily check if a user is logged in within any component:

this.$store.state.isLogged //=> returns true or false

A similar method can be used for access tokens and expiration times.

Important Update: Single-page applications can manage data without needing to refresh. However, upon manual reload, variables lose their state.

Hence, utilizing local storage ensures that even after a page reloads, the token remains accessible.

Upon logging in, save the token to localStorage. Subsequently, the user will remain logged in as long as the token persists in localStorage.

If the token is stored in a variable instead, it will not persist through page reloads.

If localStorage is not preferred, one alternative is to send a login request on each page reload, although this is not recommended.

Cookies can also serve as an option for storing authentication information.

I hope this explanation proves helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "Invalid Data Type: Not an Array - google charts" was encountered

I am struggling with an ajax call that I have set up. The issue arises when passing an array from the backend to the frontend. Upon checking the data through an alert on the frontend, everything seems fine. However, Google charts raises an error stating th ...

Prevent any unauthorized modifications to the ID within the URL by implementing appropriate security measures

I am currently developing an application using React and Express. The URL structure is similar to this: /dashboard?matchID=2252309. Users should only have access to this specific URL, and modifying the match ID should not allow them to view the page. Is ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

The Hidden Div containing NicEdit is now shrunk down to a smaller size

Attempting to integrate the NicEdit editor for a hidden textarea stored within a div has presented some challenges. The goal is for the targeted textarea's parent div to be revealed upon the user clicking a button, with the textarea's width set t ...

Using the Play framework to showcase data in an HTML table

I have a project where I am working with multiple tables, one of which is a Person table containing id and name attributes. I have successfully retrieved the data from the database using MySql and converted it into JSON. However, I am struggling to find a ...

Implementing a time to live feature in socket.io can be accomplished by setting a

After extensive searching online, I haven't been able to find any resources on how to implement the 'time-to-live' function using Socket.io. In my project, I am utilizing Node.js with express. The functionality of the mentioned time-to-live ...

What is the most reliable way to verify when knockout has completed data binding?

Implementing the panelBar feature from KendoUI into an app at work has been a challenge. It seems that KendoUI and KnockOut don't play nicely together. The issue I am facing is that the panelBar implementation is being disrupted by a dynamic knockout ...

Which Client-Side JavaScript Frameworks Pair Seamlessly With Node.js, Express.js, and socket.io.js?

Currently, I am in the process of developing a web application utilizing Node.js, Express.js, and socket.io.js on the server side. Are there any front-end frameworks (such as Agility, Angular, Backbone, Closure, Dojo, Ember, GWT, jQuery, Knockback, Knocko ...

Retrieve information from a JSON file and dynamically showcase it within a REACT component

Hey there! I'm a newbie in the world of programming and currently working on creating a carousel using Bootstrap and React. My aim is to make the Carousel images dynamic by fetching data from a local .json file. However, my current implementation seem ...

Exploring Vue JS: A guide to using the onChange event to dynamically update input values

I am currently utilizing the npm package vue-range-component to adjust values via a slider, which then dynamically updates in the input field. However, I'm encountering an issue with applying the onChange event for inputs. I need to have the ability ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Different ways to display array elements in List Item Text

Recently I started working with React and I'm using ListItemText to display values on the screen. My query is how can I utilize ListItemText to display all the elements of an array in a list. Below is the code snippet where Kpi_Before represents the ...

Unable to display divs in a stacked format using Bootstrap 5

I need help aligning div's vertically on the page. Currently, all my elements are displaying next to each other instead of stacking one below the other. body { height: 100vh; } <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

What is the unit testing framework for TypeScript/JavaScript that closely resembles the API of JUnit?

I am in the process of transferring a large number of JUnit tests to test TypeScript code on Node.js. While I understand that annotations are still an experimental feature in TypeScript/JavaScript, my goal is to utilize the familiar @Before, @Test, and @Af ...

Getting rid of the <br> tag as well as the linked <span> element

I've been experimenting with creating dynamic forms. My latest project involves a text box, an 'Add' button, and a div. The idea is that whenever a user types something into the text box and clicks the Add button, that value should appear in ...

I would appreciate your assistance in understanding how to utilize the Array concat() method in my code, and I am

I need help understanding how to use the Array concat() method and how to write pure JavaScript code according to the ECMA-262 standard. Assume O is the object we are working with. Let A be the new array created based on O with a length of 0. Set the ini ...

Issue encountered in Three.js while attempting to parse binary STL file: RangeError indicating out of bounds access problem

One of my main objectives is to import private STL files using three.js from a secure Laravel 8 storage directory. Unfortunately, the traditional method of using the .load function from STLLoader.js does not work in this scenario: const loader = new THREE ...

establish an online repository with a data storage system

As a beginner in web development, my goal is to design a website with a database that can house all archive files. I want users to have the ability to delete existing files and upload new ones directly from the web page. Utilizing HTML, CSS, and JavaScrip ...

Is it possible to assign a different array to a variable in JavaScript?

I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions: reverseArray(): designed to produce a new array that is the ...