2

I am creating MERN application and using env file but I am not able to access env variable inside react application , below is my code

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Sidebar from './components/sidebar/Sidebar';

import "./app.css";

import TopBar from './components/topbar/Topbar';
import Home from './pages/home/Home';
import AdminUsersList from './pages/adminusers/AdminUsersList';

function App() {
  return (

    

    <Router>
      <TopBar />
      <div className="container">
        <Sidebar />
        <Routes>
        <Route path='/' element={<Home/>} />
        <Route path='/users' element={<AdminUsersList/>} />
        </Routes>
        <h1>Hello {process.env.MONGO_URI}</h1>
      </div>
    </Router>
  );
}

export default App;

Want to access env variable inside function and class component of react.

3
  • where did you set the variables Commented Nov 4, 2022 at 8:17
  • need to restart the application after adding a variable in .env file use "REACT_APP_" before the variable name if you create react application using "create-react-app". PS: environment variable are visible in client side. Commented Nov 4, 2022 at 8:22
  • I already restarted it many times. Commented Nov 4, 2022 at 14:09

2 Answers 2

2

we must prefix the environment variables for class and function component with REACT_APP_.... but in server side rendering we not need to prefix it with REACT_APP words.

you should change the .env variable to REACT_APP_MONGO_URI: your mongo uri and use it inside class and function component as <h1>Hello {process.env.REACT_APP_MONGO_URI}</h1>.

Sign up to request clarification or add additional context in comments.

Comments

1

You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.


Here is the React Docs

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.