How to Set Base URL in Axios for React Applications
In React, you set the base URL for Axios by creating an Axios instance with the
baseURL option. This lets you write shorter API calls by automatically prefixing URLs with the base URL.Syntax
To set a base URL in Axios, create an Axios instance using axios.create() and pass an object with the baseURL property. This base URL will prefix all relative URLs in your requests.
axios.create(): Creates a new Axios instance.baseURL: The root URL for all requests made by this instance.
javascript
import axios from 'axios'; const apiClient = axios.create({ baseURL: 'https://api.example.com', });
Example
This example shows how to create an Axios instance with a base URL and use it inside a React component to fetch data from an API. The base URL is set once, so you only need to specify the endpoint path in requests.
javascript
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const apiClient = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', }); function Posts() { const [posts, setPosts] = useState([]); useEffect(() => { async function fetchPosts() { try { const response = await apiClient.get('/posts'); setPosts(response.data); } catch (error) { console.error('Error fetching posts:', error); } } fetchPosts(); }, []); return ( <div> <h1>Posts</h1> <ul> {posts.slice(0, 5).map(post => ( <li key={post.id}><strong>{post.title}</strong></li> ))} </ul> </div> ); } export default Posts;
Output
<div>
<h1>Posts</h1>
<ul>
<li><strong>sunt aut facere repellat provident occaecati excepturi optio reprehenderit</strong></li>
<li><strong>qui est esse</strong></li>
<li><strong>ea molestias quasi exercitationem repellat qui ipsa sit aut</strong></li>
<li><strong>eum et est occaecati</strong></li>
<li><strong>nesciunt quas odio</strong></li>
</ul>
</div>
Common Pitfalls
Common mistakes when setting the base URL in Axios include:
- Not creating an Axios instance and setting
baseURLon the default Axios export, which can cause confusion if multiple base URLs are needed. - Using absolute URLs in requests that ignore the base URL.
- Forgetting to include the protocol (http:// or https://) in the base URL.
javascript
import axios from 'axios'; // Wrong: baseURL set on default axios but requests use absolute URLs axios.defaults.baseURL = 'https://api.example.com'; // This request ignores baseURL because it uses full URL axios.get('https://otherapi.com/data'); // Right: create instance and use relative URLs const apiClient = axios.create({ baseURL: 'https://api.example.com' }); apiClient.get('/data');
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Create Axios Instance | Make a new Axios client with custom settings | const api = axios.create({ baseURL: 'https://api.com' }); |
| Set baseURL | Base URL prepended to relative request URLs | baseURL: 'https://api.com' |
| Use Relative URLs | Requests use paths relative to baseURL | api.get('/users') |
| Avoid Absolute URLs | Absolute URLs ignore baseURL | api.get('https://other.com/data') // no baseURL used |
Key Takeaways
Create an Axios instance with the baseURL option to set the root URL for requests.
Use relative URLs in requests to automatically prepend the baseURL.
Avoid mixing absolute URLs with baseURL to prevent confusion.
Always include the protocol (http:// or https://) in the baseURL.
Setting baseURL improves code clarity and makes API calls easier to manage.