Published on

Creating an Axios Instance with TypeScript

Authors

When using most popular libraries with TypeScript there is normally types defined for that library in the npm @types package normally under @types/the-popular-library.

But this is not the case for axios. Instead axios has its types defined within the axios package. To initialize a client I would do so as follows:

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
// ...
const config: AxiosRequestConfig = {
  baseURL: API_SERVER_URL,
}
const client: AxiosInstance = axios.create(config)
// ...

Note how baseURL is being used instead of url in the config. This is the url you want to automatically prepend to all requests.