useApiUrl
A composable that provides access to and management of API URL configurations. It handles storing and retrieving the API base URL from localStorage and constructs the full API URL path.
Usage
ts
import { useApiUrl } from '#imports'
// Access the current API URL configuration
const { apiUrl, apiBaseUrl, endpoints } = useApiUrl()
// Change the API base URL (triggers page reload)
const { changeBaseUrl } = useApiUrl()
changeBaseUrl('https://new-api.example.com')
Type Signature
ts
function useApiUrl(): {
apiUrl: ComputedRef<string>;
baseUrl: Ref<string>;
apiBaseUrl: ComputedRef<string>;
endpoints: ComputedRef<string[]>;
conf: ApiConfig;
changeBaseUrl: (url: string) => void;
}
Return Value
Property | Type | Description |
---|---|---|
apiUrl | ComputedRef<string> | The full API URL including the base URL and API suffix |
baseUrl | Ref<string> | The current stored base URL (from localStorage) |
apiBaseUrl | ComputedRef<string> | The resolved base URL (from localStorage or config) |
endpoints | ComputedRef<string[]> | List of available API endpoints from config |
conf | ApiConfig | The raw API configuration object |
changeBaseUrl | (url: string) => void | Method to change the base URL and reload the page |
Configuration
The composable uses the Nuxt runtime configuration to access API settings:
ts
// nuxt.config.ts
export default defineNuxtConfig({
we: {
api: {
baseUrl: 'https://api.example.com',
apiSuffix: 'api/v1',
endpoints: ['https://api.example.com', 'https://api2.example.com']
}
}
})
Persistent Storage
The selected API base URL is stored in localStorage under the key we_nuxt_$api_baseUrl
and persists across page reloads.
Endpoint switcher
We provide a pre-built component for switching API endpoints that leverages useApiUrl
internally:
vue
<template>
<div>
<h3>Using the API Endpoint Switcher Component</h3>
<we-endpoint-switcher>
<template #activator="{ attrs }">
<v-btn
size="small"
variant="outlined"
v-bind="attrs"
>
Change <v-icon icon="mdi-easter" />
</v-btn>
</template>
</we-endpoint-switcher>
</div>
</template>
This component:
- Handles displaying a dropdown/dialog to select available endpoints
- Manages the API URL changes automatically
- Uses the
#activator
slot to customize the trigger button - Provides necessary attributes via the scoped slot props