Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios baseUrl not working in react when using process.env

I have an axios helper file with a baseURL set in my react project. I have been told to remove the hard coded url and use process.env instead, but when I do this the requests no longer work for fetching the data and I get back a 404 GET error in my app.

import axios from "axios";

// axios.defaults.baseURL = "https://example-app-name.com";
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;

export default axios;

.env file in the root of my project looks like this - I am thinking maybe it cant find the .env file, I did install the dotenv library.

REACT_APP_BASE_URL=https://example-app-name.com

I get these errors

GET https://example-app-name.com 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
like image 883
walker1 Avatar asked Sep 06 '25 10:09

walker1


2 Answers

You want to make sure that dotenv is imported wherever you're using the environment variables. Or if you're using Webpack you can load it in the plugins part of your Webpack config.

const Dotenv = require("dotenv-webpack");

In webpack.config.js:

module.exports = {
plugins: [
  new Dotenv(),
  ],
}

Here is a link that talks more about environment variable in React.

like image 131
cpppatrick Avatar answered Sep 09 '25 03:09

cpppatrick


When you modify a .env file, you need to restart the React environment.

  1. Stop the React server.

  2. Add the following line to your .env file :

    REACT_APP_BASE_URL="https://example-app-name.com"

  3. Be sure to import dotenv where you use the REACT_APP_BASE_URL variable: require('dotenv').config()

  4. npm start OR yarn start

like image 43
josemartindev Avatar answered Sep 09 '25 03:09

josemartindev