You have probably heard of or used axios in your web applications. Axios is a http client for the browser and node. It makes api requests a lot easier to handle. If youβre working with Nuxt there is an official module that simplifies it even more: @nuxtjs/axios. This is what I will focus on in this article. It assumes you are familiar with Nuxt and have a project setup. I will not go in to details on how to use axios. Here you will learn how to configure axios for your needs in a Nuxt application.
How to install the axios module
In your current Nuxt project run yarn add @nuxtjs/axios
or npm install @nuxtjs/axios
depending on your setup.
Add @nuxtjs/axios
to your modules list in nuxt.config.js
.
Axios is now ready to use!
Basic usage
You can now use axios in your components and in any part that have access to the Nuxt context. The module adds axios to the context and is accessible with $axios
. You can for example use this.$axios.get(url)
or this.$axios.post(url, data)
in any .vue file.
Configure with a plugin
One way to configure axios is to create a plugin where you set all the default values. This is the same as creating any other plugin for Nuxt. The code will run before instantiating the root Vue application.
Create a plugin
- Create a file in the
plugins
folder. Name it anything you like but for exampleaxios.js
is a common naming convention.. - List the file in the plugins list in
nuxt.config.js
- Done!
Setting up the plugin
Then what should the plugin look like?
export default function ({ $axios, store }, inject) {
// Add configuration
})
In this article we will only use $axios
and store
from the context. But here you can extract more configuration objects and application specific setup options. For more information see the Nuxt context guide: https://nuxtjs.org/api/context/.
Some examples of things you could do in this plugin file:
- Set a base url for all request
- Create new axios instances and inject to the application
- Attach a token to every request
- Intercept response before using it in the application
Set a base url for all requests
If all requests are targeting the same api, for example the open Star Wars api https://swapi.dev/api/. We can configure the axios instance to have this as a base url. Which means we do not have to configure it in every request we want to make. Just add this in the plugin function:
$axios.setBaseUrl('https://swapi.dev/api/')
Using $axios
now will always have this as a base url. Making it possible to make an api call like this:
$axios.get('/people/1')
Create new axios instances and inject to the application
But what if you want to make calls to multiple apis? You can create new instances of axios with any name you prefer and inject it to the application.
Lets say we want to fetch both Star Wars and Pokemon data. We could setup two different axios instances with different base urls.
const starWarsApi = $axios.create()
const pokemonApi = $axios.create()
starWarsApi.setBaseUrl('https://swapi.dev/api')
pokemonApi.setBaseUrl('https://pokeapi.co/api/v2')
inject('starWarsApi', starWarsApi)
inject('pokemonApi', pokemonApi)
Here we use the inject
method provided by Nuxt plugins. Inject takes two arguments. The first is the key, the second one is the value. The key will be attached to the Nuxt context and will refer to the value. Nuxt will automatically add a dollar sign to the injected key. To use the axios instances we created and injected you can run:
this.$starWarsApi.get('/people/v1')
this.$pokemonApi.get('/pokemon/snorlax')
This makes it easier to use and more explicit what you are requesting. The custom created axios instances have the exact same helper functions as the orignal $axios
instance.
Attach a token to every request
If your api calls requires some kind of token this can also be setup in the plugin file. To set the authorization header on a request we must set it in the option parameter. Lets say for the sake of this example the Star Wars api required authentication. This is one way of achieving this:
this.$starWarsApi.get('/people/1', {
headers: {
Authorization: `token ${token}`,
},
})
his works fine but quickly feels annoying when you need to add this in multiple places. With the @nuxtjs/axios
module we can set this is up in the plugin file. If we want to use a Bearer token we could do like this:
const token = '123'
$axios.setToken(token, 'Bearer')
This will add the token to the Authorization header. Usually you have this token in localstorage or the vuex store. I'm used to keep the current user's token in the vuex state. In the plugin function you have access to the store from the Nuxt context. We can then check if the token exists and use it on the axios instances we created.
const token = store.state.currentUser.token
starWarsApi.setToken(token, 'Bearer')
pokemonApi.setToken(token, 'Bearer')
If you use a refresh token or update the current token in any way you can also add setToken where you update the users token. In a component or vuex store module you can for example run:
this.$starWarsApi.setToken(newToken, 'Bearer')
Intercept response before using it in the application
If you want to check the status of the response every time you make a call you can register a global interceptor. @nuxtjs/axios
provides helper methods to handle this. Lets say we want to log something specific every time the response status is 404. This could be setup using the onResponse
method.
$axios.onResponse((response) => {
if (response.status === 404) {
console.log('Oh no it returned a 404')
}
})
Complete plugin file
To wrap things up the complete plugin file (/plugins/axios.js
) with all the configuration mentioned in this article could look something like this:
export default function ({ $axios, store }, inject) {
const starWarsApi = $axios.create()
const pokemonApi = $axios.create()
starWarsApi.setBaseUrl('https://swapi.dev/api')
pokemonApi.setBaseUrl('https://pokeapi.co/api/v2')
const token = store.state.currentUser.token
starWarsApi.setToken(token, 'Bearer')
pokemonApi.setToken(token, 'Bearer')
starWarsApi.onResponse((response) => {
if (response.status === 404) {
console.log('Oh no it returned a 404')
}
})
inject('starWarsApi', starWarsApi)
inject('pokemonApi', pokemonApi)
}
This was just a quick glance on what and how you can configure axios for a better developer experience. You can do alot more and you can refactor this code for sure. This was just an example to show what you can do. I hope you found this useful.
Top comments (0)