Enhance Your HTTP-Request With Axios and TypeScript
Use OOP to make HTTP-request like a pro
Hello, world! Let me share some tips on how to boost your regular axios-instance to something powerful.
Let’s cover some basics so we know that we are on the same page. In JavaScript/TypeScript, we can make HTTP requests whether we are talking about client-side or server-side.
For client-side, you can use old-school XMLHttpRequest (please don’t do that), or modern the fetch based on Promises.
For server-side, the Node.js module https is always available for you.
Nevertheless, most of us use libraries and one of the most popular is axios.
Axios Instance
The first step for achieving cleaner code is an instance of axios. It helps us to follow the DRY principle because we use a baseUrl, share common headers between multiple requests, and attach the Authorization header.
It’s never too late to make things better, or at least try to do it.
HTTP Client
In the very beginning, we need some base http-client which will be extended to create the needed API.
It will be an abstract class (to prevent creating an instance of this base class), and its constructor will create an axios-instance. In our case, we get the base URL from the constructor. The result of axios.create will be saved to the class’s protected variable (it’s visible to its heirs only).





