Hitesh Agrawal
Hitesh Agrawal

Reputation: 121

Not able to access env variables inside react app

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.

Upvotes: 2

Views: 2833

Answers (2)

Mohammad Aziz Nabizada
Mohammad Aziz Nabizada

Reputation: 468

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>.

Upvotes: 2

todevv
todevv

Reputation: 723

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

Upvotes: 1

Related Questions