Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Ronin1702/e791a60bb748d4af3c4663705662f3df to your computer and use it in GitHub Desktop.

Select an option

Save Ronin1702/e791a60bb748d4af3c4663705662f3df to your computer and use it in GitHub Desktop.
Environment Variables in Frontend vs Backend

Environment Variables in Frontend vs Backend

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.

Table of Contents

  1. Backend Environment Variables
  2. Frontend Environment Variables
  3. Key Takeaways

Backend Environment Variables

Common Syntax

In a Node.js backend application, you can access environment variables using process.env.

const apiKey = process.env.API_KEY;

Storage

  • Stored in a .env file at the root of your project or set in the server environment.
  • Loaded using packages like dotenv or natively set in the environment where the server runs.

Security

  • More secure, as they are not exposed to the client.
  • Suitable for storing API keys and database credentials.

back to top

Frontend Environment Variables

Syntax for React and Vite Apps

Vite

In Vite, you can use import.meta.env to access environment variables.

const apiKey = import.meta.env.VITE_API_KEY;

React

In React, you can use process.env but with a REACT_APP_ prefix.

const apiKey = process.env.REACT_APP_API_KEY;

Storage for React and Vite Apps

  • Stored in a .env file at the root of your frontend project.
  • Automatically loaded and injected into your application.

Prefix Requirements

Vite Specification

  • Must be prefixed with VITE_.
  • Automatically exposed to your frontend code.

React Specification

  • Must be prefixed with REACT_APP_.
  • Only variables with this prefix are embedded into the build.

Security Concerns

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

back to top

Key Takeaways

  • In Vite, use import.meta.env.VITE_YOUR_VARIABLE to 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.
@derekmeduri
Copy link

Great write up. Needed this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment