# How to read environment variables from Node.js

> Learn how to read environment variables in Node.js through process.env, set custom ones on the command line, and load a .env file with dotenv.

Author: Flavio Copes | Published: 2018-09-10 | Updated: 2020-01-21 | Canonical: https://flaviocopes.com/node-environment-variables/

Environment variables are especially useful because we can avoid typing API keys and other sensible data in the code and have it pushed by mistake to [GitHub](https://flaviocopes.com/github/). 

And modern deployment platforms like Vercel and [Netlify](https://flaviocopes.com/netlify/) (and others) have ways to let us add environment variables through their interfaces. 

The `process` core module of Node provides the `env` property which hosts all the environment variables that were set at the moment the process was started.

Here is an example that accesses the NODE_ENV environment variable, which is set to `development` by default.

> Note: `process` does not require a "require", it's automatically available

```js
process.env.NODE_ENV // "development"
```

Setting it to "production" before the script runs will tell Node that this is a production environment.

In the same way you can access any custom environment variable you set.

Here we set 2 variables for API_KEY and API_SECRET

```bash
API_KEY=123123 API_SECRET=456456 node app.js
```

We can get them in [Node.js](https://flaviocopes.com/nodejs/) by running

```js
process.env.API_KEY // "123123"
process.env.API_SECRET // "456456"
```

You can write the environment variables in a `.env` file (which you should add to `.gitignore` to avoid pushing to GitHub), then

```sh
npm install dotenv
```

and at the beginning of your main Node file, add

```js
require('dotenv').config()
```

In this way you can avoid listing the environment variables in the command line before the `node` command, and those variables will be picked up automatically.

If you ever need to convert a `.env` file to JSON or YAML (or back), I made a free [env converter](https://flaviocopes.com/tools/env-converter/) for that.

> Note that some tools, like [Next.js](https://flaviocopes.com/nextjs/) for example, make environment variables defined in `.env` automatically available without the need to use `dotenv`.
