Accessing store state in axios plugin with Nuxt.js

I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty figuring out how to do this in Nuxt.js.

My goal is to retrieve the token value from my store and utilize it in the 'Authorization' attribute within the code snippet below.

Here is the current code I'm working with:

// /plugins/axios.js
import axios from 'axios'
import { state } from '../store'

export default () => {
    const api = axios.create({
        baseURL: process.env.BASE_URL,
        headers: {
            Authorization: `Bearer` + xxxx ACCESS STORE STATE HERE xxxx,
        },
    })

    return api
}
// nuxt.config.js
...
{
  plugins: ['~/plugins/persistedState.client.js', '~/plugins/axios'],
}
...
// store/index.js
export const state = () => ({
    token: null,
    user: null,
    isUserLoggedIn: false,
})

Since the state is returned as a function within my store/index.js, I am unable to successfully implement this and it's becoming apparent that this isn't the correct solution!

What I have attempted so far

After reviewing documentation and old discussions on this topic, it seems like I need to pass { store } as an argument. However, I encountered an error message stating

Cannot destructure property 'store' of 'undefined' as it is undefined.

For instance...

export default ({ store }) => {
    const api = axios.create({
        baseURL: process.env.BASE_URL,
        headers: {
            Authorization: `Bearer` + store.state.token,
        },
    })

    return api
}

I also experimented with setting the Authorization header directly within the store as another approach, but unfortunately, this didn't add any authorization header when making requests to the server.

// store/index.js
...
export const mutations = {
    setToken(state, token) {
        state.token = token
        state.isUserLoggedIn = !!token
        this.$axios.setHeader('Authorization', '123')
    },

I'm currently feeling stuck on this issue and would greatly appreciate any assistance or guidance. Thank you.

Answer №1

It is crucial that plugin functions remain pure and refrain from re-assigning the value of $this using a fat arrow (=>).

To access the current $axios instance and update the header for each request, you can implement the following code snippet:

// plugins/axios.js
export default function ({ $axios, store }) {
  $axios.onRequest(config => {
    const { token } = store.state

    if (token) {
      config.headers.common.Authorization = `Bearer ${token}`
    }

  })
}

Note that $axios is a package provided by @nuxtjs/axios and there is a distinction between this.$axios and this.axios especially if you have manually registered axios separately.

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

Refinement of chosen selection

Is there a way to dynamically filter the content of a table based on the selected option? I want the table to refresh every time I change the option in the select dropdown. HTML <select ng-model="selectedGrade" ng-options="grade.Id as grade.Title f ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

"Attempting to use a Chrome Extension to apply inline styles is not producing

Despite my attempts to search on Google, I have been unable to find a solution. I am currently working on developing a Chrome extension with the specific goal of changing/inserting the style.display property for one or more elements. This task would norma ...

Utilize MetroUiCSS to effortlessly integrate a sleek calendar into your AngularJS application

I'm looking to incorporate a calendar from Metro Ui CSS into my project. Here is the link to the calendar: However, I am struggling with how to activate the calendar. I have already included all necessary scripts in my index.html (3 scripts) and have ...

issue with animation occurs when the value changes while the setTimeout timer is still running

function wallpaperMediaPropertiesListener(event) { // reset animation test.stop(true); test.css('margin-left', 0); // set song title. test.text(event.title); var testWidth = test.outerWidth(); // clone text ...

The index "is_ajax" has not been defined

I attempted to create a simple login functionality using Ajax. Following a tutorial that didn't use classes and functions in PHP, I tried restructuring the code with classes and functions. However, I encountered the error: Undefined index: is_ajax He ...

Using a Vue.js directive in a template

After studying the example at https://vuejs.org/examples/select2.html, I attempted to create a reusable component for future use. Regrettably, my code is not functioning as expected. Here is the HTML structure: <template id="my-template"> <p&g ...

Retrieve the highlighted portion of a selected option within a Vue select element

Currently, I am attempting to retrieve the selected text (not value) of a select element using Vue: var App = window.App = new Vue({ el: '#app', data: { style: '5' }, computed: { calctitle: function() { return thi ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Cutting-edge framework for Single Page Applications

Can you assist me in identifying the most recent framework suitable for creating single page applications? Your help is greatly appreciated. Thank you. ...

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...

The IISNode website displays directory contents instead of launching the server.js file

Having trouble configuring IISNode to automatically serve the main server.js application file for my node application. Currently, when I navigate to http://localhost:80/ where my app is hosted, it just displays the folder contents instead of running the se ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

What is the process of decoding a URL in JavaScript?

Is there a better method to decode this URL in order to use it with JavaScript? URL: https://www.example.com/post.php?v=1&text=it's-me&20hello%0Aworld%0A At present, any occurrence of ' in the URL is causing an error and blank lines ar ...

The terminal in VS CODE is not able to detect Stripe

When I attempt to run the command 'stripe listen' in the VS Code terminal, an error is thrown: The term 'stripe' is not recognized as the name of a cmdlet, function, script file, or operable program. Please check the spelling of the ...

What is the process for making a local storage item accessible to others on a network?

Can a local storage item be accessed from any computer on the network using the same Google Chrome extension that was previously set up? ...

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

find all occurrences except for the last of a pattern in javascript

When considering the patterns below: "profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]" It is possible to extract the last part by utilizing non-capturing groups: var rege ...

Issues Persist with Vue CLI 3 and Axios - Proxy Server Failure

My VueCLI frontend application is running on http://localhost:8080 in development mode. I encountered a CORS issue when trying to access API services from http://localhost:36856. Despite setting up proxy server configuration in vue.config.js, the problem p ...