Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react evironment variables .env return undefined

I am building a react app and i need to fetch data from my api, now i want to store the api url as an environment variable. I have my .env file, i have dotenv installed, here is my code process.env.API_URL is returning undefined.

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Home from '../src/components/Home' import dotenv from  'dotenv' import path from 'path'   class App extends Component {   render() {     console.log(process.env.API_URL)     return (       <div>         <Home/>       </div>     );   } }  export default App; 
like image 258
David whyte Avatar asked Nov 10 '18 08:11

David whyte


People also ask

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.

How do you access variables in .env react?

You can access it from process. env. NODE_ENV . This variable changes based on what mode you are currently in.

How .env file works in react?

env file in our react js project. If you are using some external APIs for data you must use the . env file to store your sensitive credentials like API keys. Environment variables can also help us to store our API link in one location so that we don't have to change the link in each file manually.


1 Answers

Three things to note here

  1. the variable should be prefixed with REACT_APP_

    eg: REACT_APP_WEBSITE_NAME=hello

  2. You need to restart the server to reflect the changes.

  3. Make sure you have the .env file in your root folder(same place where you have your package.json) and NOT in your src folder.

After that you can access the variable like this process.env.REACT_APP_SOME_VARIABLE

Additional tips

  1. No need to wrap your variable value in single or double quotes.
  2. Do not put semicolon ; or comma , at the end of each line.

Read more here(my own post) and the official docs

like image 77
kiranvj Avatar answered Oct 06 '22 19:10

kiranvj