Direct Answer
To apply the principle of least privilege when using Axios, set the following options on every instance (or globally via axios.defaults):
- maxContentLength – cap the maximum response body size (default:
Infinity).
- maxBodyLength – cap the maximum request body size (default:
Infinity).
- xsrfCookieName & xsrfHeaderName – enable automatic XSRF token extraction and header injection.
- withCredentials – leave
false unless you must send cookies or HTTP auth on a cross‑origin request.
These settings should be combined with a strict request‑whitelist interceptor to block any non‑approved endpoints before the network layer is touched.
How the Settings Interact with Axios
Defaults
Axios ships with maxContentLength and maxBodyLength set to Infinity, withCredentials set to false, and no XSRF cookie or header names configured. The defaults therefore allow unlimited payloads, no credential leakage, and no automatic XSRF protection.
Instance Creation
Creating an instance with axios.create(config) merges the provided config with the defaults. The values you pass override the defaults for that instance only, keeping other instances unaffected.
Interceptors
Request interceptors run before Axios serialises and sends the request. By throwing or rejecting from the interceptor you can prevent any network traffic to disallowed URLs. Response interceptors can be used to double‑check size limits or to sanitize headers.
Minimal Secure Axios Example
// 1️⃣ Create a whitelist of allowed base URLs
const allowedHosts = [
'https://api.myapp.com',
'https://auth.myapp.com'
];
// 2️⃣ Build a secure Axios instance
const secureAxios = axios.create({
// Size limits – 2 MB for responses, 1 MB for requests
maxContentLength: 2 * 1024 * 1024,
maxBodyLength: 1 * 1024 * 1024,
// XSRF protection – server must set a cookie named "XSRF-TOKEN"
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
// Do not send credentials by default
withCredentials: false
});
// 3️⃣ Enforce the whitelist with a request interceptor
secureAxios.interceptors.request.use(request => {
const url = new URL(request.url, request.baseURL || '');
const hostAllowed = allowedHosts.some(base => url.origin === base);
if (!hostAllowed) {
return Promise.reject(new Error(`Disallowed host: ${url.origin}`));
}
return request;
}, error => Promise.reject(error));
// 4️⃣ Example usage
secureAxios.get('/users')
.then(res => console.log('Data:', res.data))
.catch(err => console.error('Request blocked or failed:', err));
What Might Change This Recommendation?
Is your application required to send credentials (cookies or HTTP auth) to a third‑party domain? If so, you would need to enable withCredentials for that specific request or instance, and ensure the target domain is on the whitelist.