When refreshing the page, the authentication token set in the Vuex store using axios in Nuxt.js/Vue.js gets reset

Here is the code snippet I am using to manage login, logout, user retrieval, and token setting for all axios requests as an auth header.

While this code works perfectly during client-side rendering - such as logging in, storing the token in cookies, etc. - I encounter an issue when refreshing the page where it seems that the token is not being set anymore. Even calling the fetch action on NuxtServerInit doesn't help. Can anyone spot where my code might be going wrong?

This is the content of my store/index.js file:

https://jsfiddle.net/3dc07yv4/

import Cookie from 'cookie'
import Cookies from 'js-cookie'

export const state = () => ({
  sidebar: true,
  token: null,
  user: null
})

export const mutations = {
  // CODE FOR TOGGLING SIDEBAR, SETTING USER, AND TOKEN
}

...

Answer №1

To tackle this issue, I came up with a solution that involves integrating an interceptor to automatically add the token to headers for every axios request. Here's how it works:

export default ({ $axios, store }) => {
  $axios.defaults.baseURL = 'https://example.com/api/'

  if (process.server) {
    return
  }

  $axios.interceptors.request.use(request => {
    request.baseURL = 'https://example.com/api/'

    // Retrieve token from auth.js store
    const token = store.state.token

    // Update axios header with token
    if (token) {
      request.headers.common['Authorization'] = token
    }
    return request
  })
}

This can be utilized as a nuxt plugin.

Answer №2

Upon encountering the same issue, I made a discovery. Although setting headers in each request was initially working for me, when navigating to the secondary page of a nested route, the token would mysteriously vanish.

const service = axios.create({
    baseURL: 'http://127.0.0.1:9012',
    timeout: 30000, 
    headers: {'Authorization': 'Bearer '+ getUser().token  }
  })

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

Creating reactive Arrays in VueJSIn this guide, we will discuss methods

Struggling to implement a hover effect on images with Vue, specifically aiming to display the second item in an image array upon hover. The challenge is maintaining updated data in the templates when changes occur. Even attempted using Computed properties ...

Steps for creating new users using a post request

I've been working on developing a chat application using react-chat-engine, and everything is running smoothly except for one issue - I'm struggling to figure out how to send a post request to create new users. Below is the code snippet I'v ...

When displaying text pulled from MYSQL in a div, white space is eliminated

I'm attempting to display a string that contains both spaces and line breaks. When I output the string as a value in an input field, the spaces are displayed correctly. <textarea rows={15} value={content} /> However, when I try to display ...

What is the best way to display a child component for every object while considering specific conditions?

I find myself wanting to use both v-for and v-if together, even though I know it's not doable. In a nutshell, my goal is to display a child component for each item in a prop. However, I also need to extract specific data from these items in order to ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

I am facing issues with my submit buttons as they are not functioning

Once I hit the submit buttons, there seems to be an issue with redirecting to another page. Could anyone assist in identifying the error within this code and why my buttons "typ1" and "cod" are not redirecting to the specified location? <?php inc ...

Adjust the image to stretch and crop appropriately to perfectly fit the specified dimensions

I have a div with an image inside of it, and the overflow of the div is set to hidden so that the image will be cropped if it exceeds the width or height. It was working correctly, but sometimes it doesn't. What could be causing this issue? Here is th ...

Leverage the Power of Two AngularJS Factories

Can I efficiently use two Factories in AngularJS by calling one from the other? Here's the Scenario: I have a Factory that returns an Array. This Factory is responsible for checking if the data to populate this Array already exists in local SQL Stor ...

I'm having trouble getting EJS files to run JavaScript module scripts

I am facing an issue with my ejs file running on localhost. I am trying to execute functions from other files that are imported with js. In the ejs file, there is a module script tag which successfully executes the code of the file specified in the src att ...

Using the Spread Operator to modify a property within an array results in an object being returned instead of

I am trying to modify the property of an object similar to this, which is a simplified version with only a few properties: state = { pivotComuns: [ { id: 1, enabled : true }, { id: 2, enabled : true ...

Best practices for handling APIs in Vue

After spending hours reading documentation and searching online for the best way to manage API calls in larger projects, I have yet to find a solution that meets my needs. My goal is to create a service or facade for the backend that can be easily integra ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

Maximizing the potential of AngularJS directives while maintaining a seamless connection to the controller

Is there a way to maintain the connection with the current controller when wrapping data with a directive? I am facing an issue where the directive within the wrapped template loses connection with the outside controller, making it impossible to execute f ...

Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues: let xhr = new XMLHttpRequest() function *statechange() { yield xhr.readyState; } let gen = statechange(); xhr.open("GET", myUrl, true); xhr.onreadystatec ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. <div className="imageGrid__container"> <di ...

How can I prevent my Vue.js application from losing focus when navigating to different components?

I am encountering an issue with my Vue.js app where the focus is lost when changing routes. Initially, when the site loads, the first element of the header component is correctly in focus as desired. However, when navigating to a different link on the site ...

Implementing icon display upon click in a Meteor application

Currently, I am in the process of developing an application using meteor and within one of the templates, I have the following code snippet. <h3> <b> <a class="viewed" href="/jobdetails/{{_id}}">{{title}}</a> </b> ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Modifying the file name during the download process using AngularJS

Looking for a solution to download a file from an ajax GET request in angularjs? Currently, I am using an invisible iframe to trigger the "Save as" popup for the downloaded file. However, I need to change the name of the file before the popup appears. If ...