Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

280
Views
nuxt store in external js file

I decided to rewrite my application from spa vue to nuxt but i faced a problem in spa, in vue i could just import store and used it but in nuxt i cant do the same, i am getting undefined object every time

in vue spa i had folder with some api services and with main api.js which include this code

import axios from 'axios'
import store from '@/store/index'

export default () => {
    return axios.create({
        baseURL: `http://myip.com/`,
        headers: {
            Authorization: `Bearer ${store.state.token}`
        }
    })
}

then in other js files i just import this api.js file and use something like this

import Api from '@/services/Api'

export default {
    register (credetinals){
        return Api().post('register', credetinals)
    },
    login (credetinals){
        return Api().post('login', credetinals)
    }
}

so i had 10 js files services where i include api.js and then in files *.vue i just import this service how can i do the same in nuxt ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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);
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!