I’ve been using React
for a while but always had a question. Why should we use Env
instead of an Object
?
Object
has advantages such as:
- Easy to edit, will reload when saved (Env required to re-run the application)
- Suggestion typing
- It is also possible to create multiple Objects for each environment, per file, or can use another way (can use more Webpack to support).
So why should we use Env
? Is it more secure or something? Thank you
2
Answers
Yeah, Env variables are more secure and consistent than Objects,
and If your code is compromised, an attacker would not be able to access your Env variables
Env helps to protect your sensitive information and reduces the risk of exposing it in your code repository.
When deciding between using env or an object in React, the choice depends on the specific requirements and nature of the data in your application.
env (environment variables) is commonly used to store sensitive or configuration-specific information. It offers benefits such as enhanced security by keeping sensitive data out of the codebase and improved configuration flexibility for different environments. It ensures consistent behavior across deployments by allowing variations in configuration.
On the other hand, using an object in React is useful for sharing data among components via props. This approach is suitable when data needs to be passed down the component hierarchy and doesn’t involve sensitive or environment-specific information.
When sharing the codebase you can share the example env file as well or the object config file if you prefer, however env is a better approach IMHO.
And then you can just add the original env file to your git ignore file and the example file with the exact same structure will be shared with other which will save a lot of time while setting up the project by just placing the env values to the file.
env files can be environment specific as well and frameworks like NextJS can detect which env file to lead in development or production just by their names like
.env.local
,.env.development.local
.And deployment platforms support env variables to be set through project deployment settings, so it’ll be easier to just change the variable value and redeploy than changing the value in the codebase and deploying again.
In conclusion, env is ideal for sensitive or configuration-specific data, while an object is useful for sharing data within React components. The choice depends on the nature and purpose of the data in your application.