Environment Variables in TypeScript
October 27, 2023
Introduction to Environment Variables
Environment variables are key-value pairs that can affect how running processes behave on a computer. They're especially useful in the following scenarios:
- Switching between development and production configurations.
- Storing secrets that shouldn't be hardcoded.
- Customizing behavior without modifying code.
Accessing Environment Variables
In Node.js (and by extension, TypeScript running in a Node environment), you can access environment variables using
Setting Environment Variables
You can set environment variables directly in the terminal:
Unix-based systems (Linux & macOS):
A common practice is to store environment variables in a
dotenv package to help load these variables:
.env file in the root of your project:
.env file in your TypeScript code:
Strong Typing Environment Variables
To leverage TypeScript's static typing with environment variables, you can define types for them.
Type Safety with Type Guards
Ensure the presence and validity of specific environment variables using type guards:
Using with Frontend Projects
If you're using TypeScript with frontend frameworks like React or Angular, bundlers like Webpack or Parcel might inline environment variables during the build process.
For example, with
create-react-app, you can prefix environment variables with
REACT_APP_ to make them available in your app:
Then in your TypeScript:
Note: Be cautious about which environment variables you expose to the frontend. Never expose sensitive data like API keys or secrets.
Tips and Best Practices
- Default values: Provide default values for your environment variables to ensure your application behaves predictably.
- Separate configs: Use different
.envfiles for different environments, e.g.,
- Secrets: Never commit
.envfiles containing secrets to version control. Add
With this knowledge, you can effectively leverage environment variables in your TypeScript projects, making your applications more flexible and environment-aware.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript