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

jQuery - Password Validation

I need help using jQuery to validate two password fields against each other. Below is the code snippet I am currently using: jQuery('#settingsForm').validate( rules : { npassword : { }, pass_check : { equ ...

How can I enable a constant condition in eslint?

I have encountered an issue with my package.json configuration. Here is the current eslintConfig generated: "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "@vue/standard" ...

Check the validity of a watched variable's value and block any assignments that do not meet the specified requirements without triggering the watch function

Check out my jsBin snippet here I am experimenting with watching a variable's value and handling failed validation by returning its previous value without triggering the watch function again. I am considering the following scenario: If validation ...

The power of Three.js comes alive when utilizing appendChild and returning elements

I recently encountered an interesting issue that I managed to resolve, but out of sheer curiosity, I would love for someone to shed some light on why this problem occurred. Below is the snippet of my HTML code: <!DOCTYPE html> <html> < ...

Error: Loop Program Encountered Unexpected Token Syntax

Every time I attempt to run this code, a syntax error (unexpected token) appears. As someone who is still learning JavaScript, I am struggling to identify the root cause of this issue. var x = 1; var example = function(){ for(var y = 0; y < ...

What's the best way to utilize multiple environment files in a Next.js application?

To dynamically change the base URL of an external backend API based on the environment, you can set different URLs for different environments. For example, .env.local=local.com, .env.staging=staging.com, .env.production=production.com To achieve this, you ...

Why do Vue/Nuxt Select field states come pre-set as valid?

My Nuxt.js form contains multiple HTML select elements, each with validation using Vuelidate. The validation is working correctly. Here is an example of one of the select boxes in my form: <select id="location" name="location" v-m ...

Displaying a JSON array response on an HTML page with JavaScript and jQuery

After receiving a JSON response with data in array format, I need to display that data on an HTML page. In my HTML structure, I have div elements for merchant name, product name, and a remove button. The JSON data consists of arrays containing the same pro ...

How can you pass an authorization token in a Next.js post request when using Django REST framework?

Is there a way to successfully pass a Django authorization token in Next.js using Axios? I attempted this method, but encountered a 404 error. let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers ...

What is the technique for hiding the bottom tab navigator upon leaving a specific screen in React Native version 5?

In the home screen, I want only the bottom tab navigator to be visible, and then hidden until the user returns to the home screen. The example provided below is tailored for working in the App.js file, but my situation is different. const Tab = createBot ...

Learn the steps to designing a responsive class using Angular2's ngClass feature

Imagine a scenario where the object models in my cloud Array include a weight key: return [ { term: '1994', weight: 0 }, { term: '2017', weight: 0 }, { term: '89th', ...

What steps can be taken to revert this Node.js module to a particular version and ensure it does not automatically update in

While using the Nodemailer module in node.js, I encountered a specific error that read as follows; [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 or see the migration guide https://github.com/andris9/Nodemailer#migration-guide] A ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

Strategies for removing duplicate items from an array of objects

My array consists of objects with the following structure: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', 'de ...

Instructions on incorporating domains into next.config.js for the "next/image" function with the help of a plugin

Here is the configuration I am currently using. // next.config.js const withImages = require("next-images"); module.exports = withImages({ webpack(config, options) { return config; }, }); I need to include this code in order to allow images from ...

What is preventing me from translating JS Canvas Image?

I've been struggling with using ctx.translate() to translate images on a canvas. No matter what I do, it just won't work. I've spent a good amount of time trying to troubleshoot the issue. Here's the snippet of code I'm working wit ...

Clicking on a React Material UI ListItem

I am trying to develop a clickable country list with icons next to each ListItem. However, I am facing an issue where only one item can be selected at a time in a single click. Upon clicking a new item, the previously selected one gets deselected first. He ...

enabling input field while making asynchronous requests with jQuery

This is the code snippet from my index.php file: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="ajax.js"></script> <script> $("input" ...

Merging angular-file-upload with multer

I am facing a challenge in integrating the angular file upload plugin with multer to create a fully Single Page Application (SPA). I am currently stuck on uploading multiple files through multer. Below is how my multer options are set up in my node route. ...

Complicated "as-label" for understanding expressions in Angular

Is it possible to set a complex label in a comprehension expression in Angular? I've searched everywhere for a solution, but I can't seem to find one. The workaround I found involves pre-populating the 'as' label attribute with the des ...