To get environment variables in React, the method depends on the tool you used to build your project. React environment variables are embedded into the application during the build process.
1. If you are using Create React App (CRA)
Variable Prefix
You must prefix your variables with REACT_APP_ for React to recognize them.
Create File
Create a .env file in the root folder (not in src).
REACT_APP_API_URL=https://api.example.com
Access in Code
Use process.env.
const apiUrl = process.env.REACT_APP_API_URL;
2. If you are using Vite
Variable Prefix
You must prefix your variables with VITE_.
Create File
Create a .env file in the root folder.
VITE_API_URL=https://api.example.com
Access in Code
Use import.meta.env.
const apiUrl = import.meta.env.VITE_API_URL;
Important Rules
Restart the Server
You must restart your development server (e.g., npm start or npm run dev) whenever you change the .env file for the changes to take effect.
Security
Never store sensitive secrets like private API keys in these files. Because React is a client-side framework, these variables are visible to anyone who inspects your app's source code in the browser.
Gitignore
Always add .env to your .gitignore file to avoid pushing local configuration or keys to your repository.
No comments:
Post a Comment