code q&a
Resources About
Question:

What is an environment variable?

Your app needs things like a database password or an API key to work, but you don’t want them sitting in your code where anyone who sees it can copy them. An environment variable holds a value like that outside your code under a name like DATABASE_PASSWORD, so your app can look it up when it runs.

You can set one in a terminal and then read it from your code. Here’s a quick example with Node.js:

export API_KEY=abc123
node -e "console.log(process.env.API_KEY)"

A Ruby on Rails app reads the same value with ENV["API_KEY"] and Python uses os.environ["API_KEY"].

Environment variables also let the same code behave differently in different places. Your laptop might use a local database and show extra error details, while the live server your users visit uses the real database and hides them.

Developers usually keep local values in a .env file, which is just a list of lines such as API_KEY=abc123 that a small library like dotenv loads when the app starts. You list that file in .gitignore, which tells Git which files to skip, so it never gets committed or ends up on GitHub. A PaaS like Vercel lets you set the real values in its dashboard or command line tool when you deploy.

Your operating system uses environment variables too. One called PATH holds a list of folders that your terminal searches through to find the right program when you type a command like git or node.

You might also like