Axios is a popular npm library for calling servers and public APIs. When an API has a clear contract, defining request and response types helps TypeScript catch errors earlier and makes development more efficient.
The examples use Next.jsโ, but you can adapt them to Reactโ, React Nativeโ, Node.jsโ, and other environments by adjusting the directory layout and how you store tokens.
We'll use JSONPlaceholderโ to test the requests.
Here's the directory structure for my app with file-based routing. Set it up in advance if it suits your project. Outside Next.js, you can focus on the structure inside the util directory.
There are several ways to manage tokens when implementing sign-in with a backend. In this example, I save and read the token in local storage. Skip this section if your API doesn't use tokens.
A request interceptor lets you modify a request before Axios sends it. For example, you can add the token to its headers.
I also log selected details of outgoing requests because that made debugging easier during development. The example logs only the necessary configuration fields.
A response interceptor lets you inspect or transform a response when it arrives. This example also logs what the server returns.
Check the response shape before extracting the data you need. The payload may be in data or nested under data.data.
The example logs more detail when an error occurs. See the shared types section for Shared.ErrorResponse.
keeps types with the same name in different scopes, which avoids naming collisions. With the ambient declarations used here, the types are also available globally without separate imports, making them easy to use in components. Choose clear names so you can tell what each type represents.
Use the examples in the JSONPlaceholder guideโ to define the request types. The following types describe requests for GET - https://jsonplaceholder.typicode.com/posts/{id} and POST - https://jsonplaceholder.typicode.com/posts.
I declare request types in a namespace and use the naming pattern {๋ฉ์๋}{API ์ด๋ฆ}{์์ณฅํํ} (method, API name, and request shape).
Write the service that uses Axios to communicate with the server. I keep my service files in apis/service.
I add a comment to each function describing the API it calls, so readers know what the endpoint does regardless of which feature uses it.
Calling the server directly with Axios or fetch may be quicker to set up. When a request fails, however, you'll need a way to handle the error consistently.
We built an Axios service that gives server calls a shared structure. Defining request and response types makes it easier to catch mistakes and work with the API.