Malik
Malik
NNuxt
Created by Malik on 3/28/2024 in #❓・help
What is "The Nuxt Way" (TM) to abstract http libs?
Hello friendly people of Nuxt, time is valuable, so I get straight to the point. I'd like to abstract a http library for global usage in a fresh nuxt application. Let's say axios, or fetch, or capacitorHttp, or whatever. Basically creating an instance with predetermined properties like the base url of an api and some headers. Base url being read from the .env file, proxied by the runtime Config. First approach was a custom nuxt plugin, but that did not seem to be usable within the pinia store. Second approach was a composable, but that failed because I got no access to the runtime Config from within the composable. Is what I am trying to achieve so out of this world? Please tell me I get a major knot in my brain and either what I try to do is dumb because of reason x, or the right way to do this is y, or I just made a stupid mistake z. That would be great 😄 Super bare-bones abstraction example with axios:
import axios from "axios";
import AuthModule from '@/repository/auth';

interface Api {
export default defineNuxtPlugin(() => {
const runtimeConfig = useRuntimeConfig();
const apiBaseUrl = runtimeConfig.app.apiUrl;

const axiosInstance = axios.create({
baseURL: apiBaseUrl as string,
});

axiosInstance.interceptors.request.use(
...
);

axiosInstance.interceptors.response.use(
...
);

const modules: Api = {
auth: new AuthModule(axiosInstance),
};

return {
provide: {
api: modules
},
};
});
import axios from "axios";
import AuthModule from '@/repository/auth';

interface Api {
export default defineNuxtPlugin(() => {
const runtimeConfig = useRuntimeConfig();
const apiBaseUrl = runtimeConfig.app.apiUrl;

const axiosInstance = axios.create({
baseURL: apiBaseUrl as string,
});

axiosInstance.interceptors.request.use(
...
);

axiosInstance.interceptors.response.use(
...
);

const modules: Api = {
auth: new AuthModule(axiosInstance),
};

return {
provide: {
api: modules
},
};
});
Thank you kindly for every hint you could give.
12 replies