Setting the global API base URL in Nuxt 3 is typically an important step, as it enables consistent management of API request base URLs across your entire application. This simplifies maintenance and future migrations. Below are the steps to configure and utilize the global API base URL in Nuxt 3:
Step 1: Configure Environment Variables
First, set the API base URL in your project's root .env file. This ensures your base URL can be adjusted for different environments (development, production, etc.).
plaintext# .env BASE_URL=https://api.example.com
Step 2: Update nuxt.config.ts File
Next, reference this environment variable in nuxt.config.ts (or nuxt.config.js, depending on your language) and set it as a global variable. This can be achieved by configuring publicRuntimeConfig, making it accessible both on the client and server sides.
typescript// nuxt.config.ts export default defineNuxtConfig({ publicRuntimeConfig: { baseUrl: process.env.BASE_URL } })
Step 3: Use useFetch in Components
In your Vue components, you can now use useRuntimeConfig to retrieve the base URL when invoking useFetch. This ensures useFetch automatically uses the configured base URL each time it is called.
vue<script setup> import { useFetch } from 'nuxt/app'; import { useRuntimeConfig } from '#imports'; const config = useRuntimeConfig(); const { data, error } = await useFetch('/users', { baseURL: config.baseUrl }); </script>
Example Explanation
Suppose your API has an endpoint /users that returns a user list. In the component script above, useFetch is called with config.baseUrl as the baseURL parameter. This means the actual request URL will be https://api.example.com/users (depending on your .env file configuration).
This approach offers the advantage that you can update the API address in one place, and the change will automatically propagate throughout the application. Additionally, by leveraging environment variables and configuration files, you can easily set different API addresses for various deployment environments (such as development, testing, and production), making management and deployment more straightforward and flexible.