Programming guides, explanations and reader checklists on whilenetworking.com

Building a REST Client with Axios: Handling JSON Responses and Error States in Frontend Apps

In modern frontend development, interacting with backend services is inevitable. While native fetch is powerful, Axios remains a preferred library for…

In modern frontend development, interacting with backend services is inevitable. While native fetch is powerful, Axios remains a preferred library for its built-in features like request/response interception, automatic JSON transformation, and robust error handling. For IT students and junior engineers, mastering Axios is not just about making HTTP requests; it is about building resilient applications that gracefully handle network failures, malformed data, and authentication issues. This guide walks you through constructing a practical REST client in a realistic workplace scenario, focusing on debugging, testing, and implementing safe error states.

Setting Up the Environment and Prerequisites

Before writing code, ensure your development environment is ready. This project assumes a Node.js environment, which is standard for most frontend toolchains like Create React App or Vite. You will need Node.js version 16 or higher installed. If you are working in a corporate setting, verify that your local machine can access the internet to pull packages from the registry, as some organizations have proxy restrictions.

Create a new project directory and initialize it with package management tools. Open your terminal and run:

mkdir axios-rest-client-demo
cd axios-rest-client-demo
npm init -y
npm install axios

The axios command installs the library into your node_modules folder. The -y flag automatically answers “yes” to prompts, speeding up the setup. Verify the installation by checking the package version:

npm list axios

You should see a version number (e.g., 1.6.x) listed. This step ensures you are not running on a broken or empty project skeleton.

Implementing Core JSON Response Handling

The primary function of a REST client is to fetch data and transform it into usable JavaScript objects. Axios automatically parses JSON responses, but you must handle the response object carefully to access nested data safely.

Create a file named api.js in your project root. This module will encapsulate your API logic, keeping your main application code clean. Define a base URL that matches your backend service or a public mock API like jsonplaceholder for testing purposes.

// api.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 5000, // Set a safe timeout to prevent hanging requests
});

// Function to get users safely
export const getUsers = async () => {
  try {
    const response = await api.get('/users');

    // Check if the response data exists before accessing properties
    if (response.data && Array.isArray(response.data)) {
      return response.data;
    } else {
      throw new Error('Unexpected response format: expected an array of users.');
    }
  } catch (error) {
    console.error('Failed to fetch users:', error.message);
    throw error; // Re-throw so the caller can handle it
  }
};

In this example, we check response.data and verify it is an array. This prevents runtime errors like “Cannot read property of undefined” if the backend returns an empty object or a string instead of JSON. Always assume external APIs might return unexpected formats during development or production outages.

Managing Error States with Interceptors

Relying solely on try/catch blocks in every component is inefficient and leads to repetitive code. Axios provides interceptors, which allow you to handle errors globally before they reach your UI components. This is crucial for implementing centralized error states, such as showing a “Network Unavailable” banner or triggering a re-authentication flow.

Update your api.js file to add an error interceptor that catches network errors and timeout exceptions:

// api.js (continued)
api.interceptors.response.use(
  null, // Pass through successful responses unchanged
  async (error) => {
    const originalRequest = error.config;

    // If the error is a network issue (e.g., CORS, DNS failure) or timeout
    if (!originalRequest || !originalRequest.url.includes('/users')) {
      return Promise.reject(error);
    }

    // Attempt to handle 401 Unauthorized errors specifically
    if (error.response?.status === 401) {
      // In a real app, you would redirect to a login page here
      console.warn('Authentication failed. User needs to re-login.');
      return Promise.reject(error); 
    }

    // Generic error handling for 5xx server errors or timeouts
    if (error.code === 'ECONNABORTED' || !error.response) {
      return Promise.reject({
        message: 'Connection timed out or network unavailable.',
        type: 'NETWORK_ERROR'
      });
    }

    // Pass other errors up to the caller
    return Promise.reject(error);
  }
);

This configuration distinguishes between application logic errors (like missing data) and infrastructure failures (like timeouts). By returning a standardized error object, your frontend components can render specific messages based on the type property.

Debugging and Verification Steps

When developing a REST client, debugging is often more important than writing new features. Common mistakes include ignoring CORS errors or failing to inspect network traffic. Use the browser’s Developer Tools (F12) to verify your implementation.

Navigate to the Network tab in your browser console before running your app. Look for the request to /users.
* Status Code 200: Success. Click on the request and expand “Response” to see the raw JSON payload.
* Status Code 404: The endpoint does not exist. Check your baseURL or path spelling.
* Status Code 500: Server-side error. Check the server logs if you have access, or assume the backend is down.
* No Response: This usually indicates a CORS policy violation or a network timeout.

To simulate an error state for testing without breaking production, use the json-server tool to mock data locally. Start a local server:

npx json-server --watch db.json --port 3001

This creates a fake database that mimics a real API. You can then modify your axios configuration to point to http://localhost:3001 to test error handling logic in isolation. Always verify that your error messages are user-friendly and do not expose sensitive technical details like stack traces to end-users.

Student Practice Task: Building a Resilient Dashboard

To solidify these concepts, complete the following task. This exercise bridges academic theory with industry application.

Task: Create a simple dashboard component that lists users and handles errors gracefully.
1. Initialize a new React project using Vite (npm create vite@latest my-dashboard -- --template react).
2. Install Axios in the project (npm install axios).
3. Create an App.jsx file. Import the getUsers function from your custom api.js.
4. Implement a state variable users and a loading/error state variable status.
5. Use useEffect to call getUsers(). Update the state based on the result or error.
6. Render three distinct UI sections:
* A loading spinner while the request is pending.
* A list of user cards if the data loads successfully.
* An error message box if a network error or 401 occurs, using the custom error object from your interceptor.

Expected Output: When you run npm run dev, open your browser to http://localhost:5173. You should see a clean interface. If you intentionally stop your server (simulating an offline backend), the app should display “Network Unavailable” instead of crashing or showing a blank screen.

Industry Application and Final Checklist

In a professional environment, building a REST client is rarely just about fetching data; it is about maintaining system integrity. Your Axios configuration should be part of your repository’s shared utilities, not scattered across individual components.

Verification Checklist for Production Deployment:
* [ ] Timeouts Configured: Ensure every request has a timeout property set (e.g., 5000ms) to prevent blocking the UI thread.
* [ ] CORS Headers Checked: Verify that your backend sends appropriate Access-Control-Allow-Origin headers if using a different domain.
* [ ] Error Types Defined: Ensure your interceptors return consistent error objects (e.g., { type: 'AUTH_ERROR' }) so UI components can switch views reliably.
* [ ] Logging Strategy: Use environment variables to control logging. Disable detailed console.error in production builds to avoid leaking sensitive info.
* [ ] Retry Logic: Consider adding a retry interceptor for transient network errors (like 503 Service Unavailable), but only for idempotent requests (GET, HEAD).

By following these steps, you move beyond basic API consumption to building robust, maintainable frontend applications capable of handling the unpredictable nature of real-world networks.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.