How to create an Axios instance with url and headers defined

axios
http

Sometimes you need multiple axios calls that all have the same headers and base url. To avoid having to repeat the headers & base url details in each axios function you can create an axios instance that has the relevant details baked into it. You then simply call that instance, with its appropriate http method.

A common use for this pattern is where you need to pass an auth token in the headers.

import axios from 'axios' const github = axios.create({ baseURL: process.env.REACT_APP_GITHUB_URL, headers: { Authorization: `token ${process.env.REACT_APP_GITHUB_TOKEN}` }, }) export const searchUsers = async (text) => { const params = new URLSearchParams({ q: text, }) const response = await github.get(`/search/users?${params}`) return response.data.items } export const getUser = async (username) => { const response = await github.get(`/users/${username}`) return response.data }