walker1
walker1

Reputation: 361

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

Upvotes: 4

Views: 19520

Answers (2)

cpppatrick
cpppatrick

Reputation: 769

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.

Upvotes: 2

josemartindev
josemartindev

Reputation: 1426

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

Upvotes: 2

Related Questions