Environment variables are a way to store configuration settings for your applications. They are key-value pairs that are outside of the application code. Although environment variables work in a similar fashion in both frontend and backend applications, there are some specific considerations for each.
In a Node.js backend application, you can access environment variables using process.env.
const apiKey = process.env.API_KEY;- Stored in a
.envfile at the root of your project or set in the server environment. - Loaded using packages like
dotenvor natively set in the environment where the server runs.
- More secure, as they are not exposed to the client.
- Suitable for storing API keys and database credentials.
In Vite, you can use import.meta.env to access environment variables.
const apiKey = import.meta.env.VITE_API_KEY;In React, you can use process.env but with a REACT_APP_ prefix.
const apiKey = process.env.REACT_APP_API_KEY;- Stored in a
.envfile at the root of your frontend project. - Automatically loaded and injected into your application.
- Must be prefixed with
VITE_. - Automatically exposed to your frontend code.
- Must be prefixed with
REACT_APP_. - Only variables with this prefix are embedded into the build.
- Less secure, as they are exposed to the client.
- Not suitable for storing sensitive information like API keys or database credentials, unless they are public.
- In Vite, use
import.meta.env.VITE_YOUR_VARIABLEto access environment variables. - In React, use
process.env.REACT_APP_YOUR_VARIABLE. - Backend environment variables are more secure for storing sensitive information.
- Always prefix your environment variables in frontend applications as per the framework's requirements to ensure they are correctly embedded into the build.
Great write up. Needed this