0

How I can set baseUrl for axios using npm param?

I would like to write command like this npm run build --baseUrl={url address} and in axios config set baseURL param to param from command.

It is possible ?

1 Answer 1

3

I don't think it is possible if you call that --baseUrl like that, as if you do it like that, you're going to have to define --baseUrl for npm start and other scripts, and you'll quickly end up with a spaghetti code.

I humbly suggest a way to mitigate this issue:

  • Create an .env file that is filled with your environment variables for development. Add this to .gitignore and don't push this into your production server. This file is not used for production.
  • Add a new BASE_URL variable, like:
BASE_URL=http://YOUR_API_LOCATION/
  • Use libraries like dotenv (install by npm i dotenv) so you can read .env files.

  • Create a new utility for axios, let's say:

// client.js
const axios = require('axios');
const dotenv = require('dotenv');

// get all environment variables here.
dotenv.config({ path: '.env' });

// create a new axios instance with the base url from your '.env' file.
const axiosInstance = axios.create({
  baseURL: process.env.BASE_URL,
  /* other custom settings */
});

module.exports = axiosInstance;

You can reuse your axiosInstance like this:

// request.js
const axiosCustomClient = require('./client');

axiosCustomClient.get('relative/path/to/your/api');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.