Milind Daraniya

Axios: How to Set Base URL in React

Published August 30th, 2023 23 min read

Hello, React developers! In this tutorial, we'll explore how to set a base URL for Axios in a React application. Axios is a popular JavaScript library used for making HTTP requests, and setting a base URL can help simplify and centralize the endpoint configuration in your project. Let's dive into this step-by-step guide with a practical example!

Step 1: Set Up a New React Project 
If you don't have a React project yet, you can create one using Create React App (CRA). Open your terminal and run the following command:

npx create-react-app axios-base-url-example

Step 2: Install Axios 
Navigate to your project directory and install Axios by running:

npm install axios

Step 3: Create a Separate Axios Instance with Base URL 
Now, let's create a separate Axios instance with a base URL. This way, all the HTTP requests made using this instance will automatically use the specified base URL. Create a file named api.js in the src directory of your React project:

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

const instance = axios.create({
  baseURL: 'https://api.example.com/', // Replace with your base URL
  timeout: 5000, // Set the timeout for requests (optional)
  headers: { 'Content-Type': 'application/json' }, // Set common headers (optional)
});

export default instance;

Step 4: Use Axios with Base URL in Your Components 
Now that you've set up the Axios instance with the base URL, you can use it in your components to make HTTP requests. For example, create a file named UserList.js in the src directory:

// src/UserList.js
import React, { useEffect, useState } from 'react';
import api from './api';

const UserList = () => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // Fetch user data from the API using Axios with the base URL
    api.get('/users')
      .then(response => setUsers(response.data))
      .catch(error => console.error(error));
  }, []);

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

Step 5: Render the Component in App.js 
Now, let's render the UserList component in the App.js file. Open the App.js file in the src directory and update it as follows:

// src/App.js
import React from 'react';
import UserList from './UserList';

function App() {
  return (
    <div>
      <h1>React Axios Base URL Example</h1>
      <UserList />
    </div>
  );
}

export default App;

Step 6: Test the Application 
Start your React development server by running the following command in your project's root directory:

npm start

Visit http://localhost:3000 in your web browser. You should see the "User List" heading and a list of users fetched from the API using Axios with the base URL.

Congratulations! 🎉 You've successfully set a base URL for Axios in your React application.

With this knowledge, you can now centralize your API configuration and simplify HTTP requests throughout your React project using Axios with a base URL.