Onjsdev

Share


How To Set Base URL In Axios Using Different Ways


By onjsdev

Dec 4th, 2023

Axios is a popular JavaScript library for making HTTP requests in javascript applications. While using Axios, if you want to simplify the process of sending requests to the same server, setting dynamically a base url may be a good idea.

In this article, we'll explore different methods to achieve this. Let's start with the first method.

Global Configuration

One straightforward approach is to globally configure Axios with a base URL. This ensures that every request made with Axios originates from the specified URL. Here's an example of how to set the base URL globally:

// Import Axios library
import axios from 'axios';

// Set the base URL
axios.defaults.baseURL = 'https://api.example.com';

// Now, all requests will be sent to https://api.example.com

This method is proper when your application communicates with only a single API server.

Instance Configuration

In some scenarios, you may need to communicate with multiple API servers within the same application. To handle this, you can create an Axios instance for each server and set the base URL individually.

Here's an example:

// Import Axios library
import axios from 'axios';

// Create an instance for API server 1
const apiServer1 = axios.create({
  baseURL: 'https://api-server1.example.com',
});

// Create an instance for API server 2
const apiServer2 = axios.create({
  baseURL: 'https://api-server2.example.com',
});

// Now, you can use apiServer1 or apiServer2 for requests

Using Interceptors

Axios interceptors allow you to run your code or modify the request or response before the request is sent or after the response is received. This provides an opportunity to dynamically set the base URL based on certain conditions.

Here's an example:

// Import Axios library
import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use((config) => {
  // Set the base URL based on some condition
  config.baseURL = determineBaseURL();

  return config;
});

// Function to determine the base URL dynamically
function determineBaseURL() {
  // Your logic to determine the base URL
  // ...

  return 'https://dynamic-api.example.com';
}

This method is useful when the base URL needs to be determined dynamically during runtime.

Conclusion

Setting the base URL in Axios can be accomplished in various ways, depending on the requirements of your application. Whether you choose to configure it globally, per instance, or dynamically using interceptors, it is straigtforward operation.

Thank you for reading