VS Code SetupIntermediate

How to Add Environment Variables to a VS Code Debug Configuration

Pass environment variables to your app while debugging, either inline in launch.json or from a .env file, so secrets and config load correctly.

8 minIntermediate

Most real apps read configuration from environment variables: an API key, a database URL, a port. When you debug from VS Code those variables are not set unless you tell the debugger about them. This guide shows two clean ways to provide them, directly in launch.json and from a .env file, so your app behaves the same under the debugger as it does in a normal run.

What you need

  • A Node.js project with an existing launch.json debug config
  • An app that reads from process.env
  • A few minutes

Step 1: Add variables inline with env

Open .vscode/launch.json and add an env object to your configuration. Each key becomes an environment variable available to your app while you debug. This is fine for non-secret values like a port or a mode flag.

.vscode/launch.json
{
  "type": "node",
  "request": "launch",
  "name": "Launch with env",
  "program": "${workspaceFolder}/index.js",
  "env": {
    "NODE_ENV": "development",
    "PORT": "4000"
  }
}

Step 2: Keep secrets in a .env file instead

Do not put real secrets like API keys directly in launch.json, because it is committed to git. Put them in a .env file that your .gitignore excludes, then point the debugger at it with envFile.

.env
API_KEY=sk-your-real-key-here
DATABASE_URL=postgres://localhost:5432/app
.vscode/launch.json
{
  "type": "node",
  "request": "launch",
  "name": "Launch with .env",
  "program": "${workspaceFolder}/index.js",
  "envFile": "${workspaceFolder}/.env"
}
Never commit .env
Add .env to your .gitignore before you put any secret in it. If a key is ever committed and pushed, treat it as leaked and rotate it.

Step 3: Read a variable in your code

In your app, read the values from process.env. They are plain strings, so convert PORT to a number where needed.

index.js
const port = Number(process.env.PORT) || 3000
console.log("NODE_ENV is", process.env.NODE_ENV)
console.log("Listening on", port)

Step 4: Run and confirm

Press F5 to start debugging with your chosen configuration. Check the Debug Console for the printed values; they should match what you set. If a variable is undefined, the env block or the envFile path is wrong.

VS Code - Debug Console
DEBUG CONSOLE
------------------------------------
NODE_ENV is development
Listening on 4000
Environment values printed at startup.

Result

Your debug session now loads the right configuration, with safe values inline and secrets kept out of source control in a .env file. The app runs under the debugger exactly as it does in production-like setups.

Watch related tutorials

Tags
#debug#environment-variables#launch-json#dotenv#nodejs