Axios
Secure and Easy Axios integration with Nuxt.js.
📖 Release Notes
Table of Contents
Features
- Automatically set base URL for client & server side
- Exposes
setToken
function to $axios
so we can easily and globally set authentication tokens - Throws nuxt-friendly errors and optionally redirect on specific error codes
- Automatically enables
withCredentials
when requesting to base URL - Proxy request headers in SSR (Useful for auth)
- Fetch Style requests
Setup
Install with npm:
>_ npm install @nuxtjs/axios
Install with yarn:
>_ yarn add @nuxtjs/axios
nuxt.config.js
{
modules: [
'@nuxtjs/axios',
],
axios: {
}
}
Usage
Component
asyncData
async asyncData({ app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
return { ip }
}
methods
/created
/mounted
/etc
methods: {
async fetchSomething() {
const ip = await this.$axios.$get('http://icanhazip.com')
this.ip = ip
}
}
Store nuxtServerInit
async nuxtServerInit ({ commit }, { app }) {
const ip = await app.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
Store actions
(Needs Nuxt >= 1.0.0-RC8)
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}
Options
You can pass options using module options or axios
section in nuxt.config.js
baseURL
- Default:
http://[HOST]:[PORT]/api
Base URL is required for requests in server-side & SSR and prepended to all requests with relative path.
You can also use environment variable API_URL
which overrides baseURL
.
browserBaseURL
Base URL which is used in client side prepended to all requests with relative path.
You can also use environment variable API_URL_BROWSER
which overrides browserBaseURL
.
- If
browserBaseURL
is not provided it defaults to baseURL
value.
- If hostname & port of
browserbaseURL
are equal to nuxt server, it defaults to relative part of baseURL
.
So if your nuxt application is being accessed under a different domain, requests go to same origin and prevents Cross-Origin problems.
credentials
Adds an interceptor to automatically set withCredentials
config of axios when requesting to baseUrl
which allows passing authentication headers to backend.
debug
Adds interceptors to log all responses and requests
In SSR context, sets client request header as axios default request headers.
This is useful for making requests which need cookie based auth on server side.
Also helps making consistent requests in both SSR and Client Side code.
NOTE: If directing requests at a url protected by CloudFlare's CDN you should set this to false to prevent CloudFlare from mistakenly detecting a reverse proxy loop and returning a 403 error.
- Default
['host', 'accept']
Only efficient when proxyHeaders
is set to true. Removes unwanted request headers to the API backend in SSR.
redirectError
This option is a map from specific error codes to page which they should be redirect.
For example if you want redirecting all 401
errors to /login
use:
axios: {
redirectError: {
401: '/login'
}
}
requestInterceptor
Function for manipulating axios requests. Useful for setting custom headers,
for example based on the store state. The second argument is the nuxt context.
requestInterceptor: (config, { store }) => {
if (store.state.token) {
config.headers.common['Authorization'] = store.state.token
}
return config
}
responseInterceptor
responseInterceptor: (response, ctx) => {
return response
}
Function for manipulating axios responses.
init
Function init(axios, ctx)
to do additional things with axios. Example:
axios: {
init(axios, ctx) {
axios.defaults.xsrfHeaderName = 'X-CSRF-TOKEN'
}
}
disableDefaultErrorHandler
If you want to disable the default error handler for some reason, you can do it so
by setting the option disableDefaultErrorHandler
to true.
errorHandler
- Default: (Return promise rejection with error)
Function for custom global error handler.
This example uses nuxt default error page.
If you define a custom error handler, the default error handler provided by this package will be overridden.
axios: {
errorHandler (errorReason, { error }) {
error('Request Error: ' + errorReason)
}
},
Helpers
Fetch Style requests
Axios plugin also supports fetch style requests with $
prefixed methods:
let data = (await $axios.get('...')).data
let data = await $axios.$get('...')
Axios instance has a helper to easily set any header.
Parameters:
- name: Name of the header
- value: Value of the header
- scopes: Send only on specific type of requests. Defaults
- Type: Array or String
- Defaults to
common
meaning all types of requests - Can be
get
, post
, delete
, ...
this.$axios.setHeader('Authorization', '123')
this.$axios.setHeader('Authorization', '456')
this.$axios.setHeader('Content-Type', 'application/x-www-form-urlencoded', ['post'])
this.$axios.setHeader('Content-Type', false, ['post'])
setToken(token, type, scopes='common')
Axios instance has an additional helper to easily set global authentication header.
Parameters:
- token: Authorization token
- type: Authorization token prefix(Usually
Bearer
). - scopes: Send only on specific type of requests. Defaults
- Type: Array or String
- Defaults to
common
meaning all types of requests - Can be
get
, post
, delete
, ...
this.$axios.setToken('123')
this.$axios.setToken('456')
this.$axios.setToken('123', 'Bearer')
this.$axios.setToken('123', 'Bearer', ['post', 'delete'])
this.$axios.setToken(false)
Dynamic API Backend
Please notice that, API_URL
is saved into bundle on build, CANNOT be changed
on runtime! You may use proxy module for dynamically route api requests to different backend on test/staging/production.
Example: (nuxt.config.js
)
{
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: [
['/api', { target: process.env.PROXY_API_URL || 'http://www.mocky.io', pathRewrite: { '^/api': '/v2' } }]
]
}
Start Nuxt
[AXIOS] Base URL: http://localhost:3000/api | Browser: /api
[HPM] Proxy created: /api -> http://www.mocky.io
[HPM] Proxy rewrite rule created: "^/api" ~> "/v2"
Now you can make requests to backend: (Works fine in both SSR and Browser)
async asyncData({ app }) {
const nuxt = await app.$axios.$get('59388bb4120000dc00a672e2')
return {
nuxt
}
}
Details
License
MIT License
Copyright (c) 2017 Nuxt Community