[Vuejs]-Nuxt store in external js file

0👍

If you add your state under the /store/index.js it will automatically append in the application, you dont need to import it in your file.

What you can do is try to check the state using:

window.$nuxt.$store.state

Also dont forget to add a condition process.browser since you want to check it in browser.

Here is what I did in my api.js file for your reference:

// Libraries
import axios from 'axios';

// API Instance
export const instance = axios.create({
    baseURL: 'http://myip.com/',
    headers: {},
    validateStatus: status => {
        return status;
    },
});

// API Interceptors
instance.interceptors.request.use(config => {
    if (process.browser) {
        const userToken = window.$nuxt.$store.getters.getUserToken;
        // Set Authorization token
        if (userToken) {
            config.headers['Authorization'] = `Bearer ${userToken}`;
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

Leave a comment