@whoj/nuxt3-axios
v2.0.1
Published
An alternative to @nuxtjs/axios for Nuxt 3
Readme
@whoj/nuxt3-axios
A drop-in replacement for
@nuxtjs/axiossupporting Nuxt 3 & 4 with SSR, composables, and auto-imports.
Note: This module is designed as an alternative to the official @nuxtjs/axios which only supports Nuxt 2. For complete documentation and usage patterns from the original module, visit axios.nuxtjs.org.
Features
- ✨ Nuxt 3 & 4 Compatible - Works seamlessly with both versions
- 🔄 SSR-Aware - Automatic client/server context detection
- 🎯 Composables -
$axios()anduseAxios()with auto-import support - 📦 Type-Safe - Full TypeScript support with IntelliSense
- 🔌 Retry Logic - Built-in retry mechanism with
axios-retry - 📊 Progress Indicator - Integration with Nuxt's loading indicator
- 🔐 Credentials Support - Automatic
withCredentialsfor same-origin requests - 🐛 Debug Mode - Request/response logging for development
Installation
npm install @whoj/nuxt3-axios
# or
pnpm add @whoj/nuxt3-axios
# or
yarn add @whoj/nuxt3-axiosQuick Start
1. Register Module
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@whoj/nuxt3-axios'],
axios: {
baseURL: 'https://api.example.com',
credentials: true,
progress: true,
debug: true, // Enable in development
autoImport: {
enabled: true // Auto-import $axios and useAxios
}
}
})2. Using the Composable
// Auto-imported when autoImport.enabled: true
const axios = $axios()
// Make requests
const data = await axios.$get('/users')
const user = await axios.$post('/users', { name: 'John' })
// With useAxios (cached with useAsyncData)
const { data, pending, error } = await useAxios('/users')3. Global Injection (Optional)
// nuxt.config.ts
export default defineNuxtConfig({
axios: {
global: true,
alias: 'axios' // Inject as $axios
}
})
// Use in components
const { $axios } = useNuxtApp()
const data = await $axios.$get('/users')Configuration Options
You can pass different options using the axios property in your nuxt.config.ts:
export default defineNuxtConfig({
axios: {
// Axios options here
}
})Runtime Config
The use of runtime config is recommended for environment variables in production.
Supported options:
baseURLbrowserBaseURL
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@whoj/nuxt3-axios'],
axios: {
baseURL: 'http://localhost:4000' // Used as fallback if no runtime config is provided
},
runtimeConfig: {
axios: {
baseURL: process.env.BASE_URL
},
public: {
axios: {
browserBaseURL: process.env.BROWSER_BASE_URL
}
}
}
})prefix, host and port
These options are used for the default values of baseURL and browserBaseURL.
They can be customized with API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) environment variables.
Default value of prefix is /.
baseURL
- Default:
http://[HOST]:[PORT][PREFIX]
Defines the base URL which is used and prepended to make server side requests.
Environment variable API_URL or NUXT_AXIOS_BASE_URL can be used to override baseURL.
browserBaseURL
- Default:
baseURL
Defines the base URL which is used and prepended to make client side requests.
The environment variable API_URL_BROWSER or NUXT_PUBLIC_AXIOS_BROWSER_BASE_URL can be used to override browserBaseURL.
https
- Default:
false
If set to true, http:// in both baseURL and browserBaseURL will be changed into https://.
progress
- Default:
true
This option shows a loading bar while making requests integrating Nuxt's progress bar. This is active only in the browser, and when loading bar is enabled and available.
You can also disable the progress bar in specific requests using the progress option in an inline request configuration:
$axios.$get('URL', { progress: false })retry
- Default:
false
Automatically intercept failed requests and retries them whenever possible using axios-retry.
By default, number of retries will be 3 times, if retry value is set to true. You can change it by passing an object with retry options:
axios: {
retry: { retries: 3 }
}credentials
- Default:
false
Adds an interceptor that automatically sets withCredentials axios configuration when issuing a request to baseURL that needs to pass authentication headers to the backend.
debug
- Default:
false
Adds interceptors that log axios request and responses.
proxyHeaders
- Default:
true
In SSR context, this option sets client request headers as default headers for the axios requests. This is useful for making requests which need cookie based auth on server side. This also helps making consistent requests in both SSR and Client Side code.
proxyHeadersIgnore
- Default:
['accept', 'cf-connecting-ip', 'cf-ray', 'content-length', 'content-md5', 'content-type', 'host', 'if-modified-since', 'if-none-match', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-proto']
This is useful and effective only when proxyHeaders is set to true. It removes unwanted request headers to the API backend in SSR.
Ignoring headers like x-forwarded-host is necessary to avoid confusing reverse proxies (like Nginx and CloudFlare) and avoid causing proxy loops.
headers
Headers added to all requests. If provided, will be merged with the defaults.
{
common: {
'Accept': 'application/json, text/plain, */*',
'Access-Control-Allow-Origin': '*',
'X-Requested-With': 'XMLHttpRequest'
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {}
}- NOTE: Do NOT include any credentials or tokens here. They can be easily accessed.
- NOTE: These headers take effect on ALL requests. Wherever possible, consider providing headers on specific requests instead.
autoImport
- Default:
{ enabled: false, imports: { $axios: '$axios', useAxios: 'useAxios' }, priority: 1 }
Controls auto-import behavior for composables:
axios: {
autoImport: {
enabled: true, // Enable auto-imports
imports: {
$axios: '$axios',
useAxios: 'useAxios'
},
priority: 1
}
}global
- Default:
false
When enabled, injects axios instance globally in your Nuxt app:
axios: {
global: true,
alias: 'axios' // Customize the injection key (default: 'axios')
}Extended Methods
The module extends axios with utility methods that automatically unwrap response data:
// Standard axios
const response = await axios.get('/users')
const data = response.data // Manual unwrapping
// Extended methods (auto-unwrap)
const data = await axios.$get('/users') // Returns data directlyAvailable extended methods:
$request,$get,$delete,$head,$options$post,$put,$patch$postForm,$putForm,$patchForm
Helper Methods
setBaseURL(baseURL)
Dynamically set the base URL for axios instance.
setHeader(name, value, scopes?)
Set a header for axios requests. Scopes can be 'common', 'get', 'post', 'delete', 'patch', 'put', 'head'.
const axios = $axios()
// Set for all requests
axios.setHeader('Authorization', 'Bearer token')
// Set for specific methods
axios.setHeader('Content-Type', 'application/json', ['post', 'put'])setToken(token, type?, scopes?)
Convenient method to set the Authorization header.
const axios = $axios()
// Set bearer token
axios.setToken('your-token', 'Bearer')
// Or just the token
axios.setToken('your-token')Interceptor Helpers
const axios = $axios()
// Request interceptors
axios.onRequest(config => {
console.log('Making request to ' + config.url)
})
axios.onRequestError(error => {
console.error('Request error:', error)
})
// Response interceptors
axios.onResponse(response => {
console.log('Response:', response.status)
})
axios.onResponseError(error => {
console.error('Response error:', error)
})
// Error interceptor
axios.onError(error => {
console.error('Error:', error)
})
// Auth error helper
axios.onAuthError(error => {
console.error('Authentication error:', error)
})Environment Variables
Set base URLs via environment variables (highest priority):
# Server-side base URL
API_URL=https://api.example.com
# or
NUXT_AXIOS_BASE_URL=https://api.example.com
# Client-side base URL
API_URL_BROWSER=https://api.example.com
# or
NUXT_PUBLIC_AXIOS_BROWSER_BASE_URL=https://api.example.comMigrating from @nuxtjs/axios
This module is designed as a drop-in replacement. Most configurations work identically:
- Replace
@nuxtjs/axioswith@whoj/nuxt3-axiosin your dependencies - Update
nuxt.config.tsmodules array - Enable
autoImport.enabled: trueif you want auto-imported composables - For proxying requests, use Nuxt 3's built-in Nitro server with
routeRules:export default defineNuxtConfig({ nitro: { routeRules: { '/api/**': { proxy: 'http://api.example.com/**' } } } }) - Refer to axios.nuxtjs.org for detailed usage patterns
Development
# Install dependencies
pnpm install
# Develop with playground
pnpm dev
# Build the module
pnpm build
# Run linter
pnpm lint
# Run tests
pnpm testResources
- Original @nuxtjs/axios Documentation - Comprehensive guide and API reference
- Axios Documentation - Core axios library docs
- Nuxt 3 Documentation - Nuxt 3 framework guide
