I have stored different API URLs in my .env file, specifically for development and production environments. Here is how I access these URLs:
const isProdEnv = process.env.NODE_ENV === 'production'
const DEV_API_URL = "https://example-stage.herokuapp.com/v1/"
const PROD_API_URL = "https://example.herokuapp.com/v1/"
const API_URL = isProdEnv ? PROD_API_URL : DEV_API_URL
In addition to that, I have set up a runtime configuration in my Nuxt config file as follows:
runtimeConfig: {public: { apiURL: process.env.API_URL || "https://example-stage.herokuapp.com/v1/", }, },
To effectively utilize this API URL across various components, I created a composable called UseApiUrl
. The code for this composable is designed to extract the API URL from the runtime configuration:
export default function useApiUrl() {
const config = useRuntimeConfig();
const apiUrl = ref(config.public.apiURL);
return { apiUrl };
}
This composable is then integrated into my services/api.js file like so:
import useApiUrl from "~/composables/useApiUrl";
const { apiUrl } = useApiUrl();
export const HTTP = {
baseURL: apiUrl.value,
headers: {
"Content-Type": "application/json",
},
};
The HTTP object defined in my request.js file serves as a centralized hub for handling HTTP requests and managing headers:
import { HTTP } from "./api";
export default class Req {
constructor() {
// logic for setting authorization header based on token presence
}
// implementation of get, post, put, patch, delete methods using fetch API
}
However, upon execution, I encountered the following error:
[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function.
If anyone has insights on how to properly expose and utilize the API_URL outside of component files, your assistance would be highly appreciated.
The objective is to seamlessly incorporate the API_URL within the functionalities of the api.js file.