I'm using nuxt-bridge in order to migrate a Nuxt 2 app to Nuxt 3.
Nuxt 2
There are some services that are located in a separate .js file, that have to access different url's that are provided through environmental variables. The api calls are made with axios, with a simple structure like this
/services/service.js
const apiClient = axios.create({
baseURL: process.env.API_URL,
})
export const fetchApiData = () => {
return apiClient.get()
}
Then in the vuex store, there is a method that calls this service on init
import { fetchApiData } from '~/services/service'
export const state = () => ({
apiData: '',
});
export const mutations = {
SET_API_DATA(state, data) {
state.apiData = data;
},
};
export const actions = {
loadApiData({ commit }) {
const myApiData = fetchApiData();
commit('SET_API_DATA', myApiData);
},
};
Nuxt-bridge
In nuxt-bridge I had to change a bit the approach, as I can just call process.env on the server side. So on
nuxt.config.ts
export default defineNuxtConfig({
components: [
runtimeConfig: {
public: {
API_URL: process.env.API_URL,
},
},
});
And now I have to make the env variable available to the service, thus I turned it into a composable, so in
composables/useApi.js
import axios from 'axios'
export const useApi = () => {
const config = useRuntimeConfig();
const apiClient = axios.create({
baseURL: process.env.API_URL,
})
const fetchDataFromApi = () => {
return apiClient.get();
};
return { fetchDataFromApi };
};
And then I try to import the composable on the store, but then I get an error
nuxt app instance unavailable
What would be the way to get this service structure working? I leave a working repo https://stackblitz.com/edit/github-dwx287-oygyaf?file=composables%2FuseApi.js,nuxt.config.ts,pages%2Findex.vue,store%2Findex.js.
PS: I'm aware that Nuxt 3 enforces Pinia as store management, but I would like to be able to keep vuex for the moment as I have a lot of code there, and I'd like to make a more progressive migration.
Thanks in advance!