Course contentsShow
← JavaScript
Lesson 2516 of 2,72351. Package ManagementFree lesson

Environment Variables in Scripts

Accessing and setting environment variables within npm scripts using cross-env for portability.

Environment Variables in Scripts

You'll learn how to access and set environment variables in npm scripts across different operating systems using cross-env.

What Are Environment Variables in Scripts?

Environment variables are dynamic values your scripts can read to change behavior without modifying code. In npm scripts, you might want different settings for development versus production, or pass secret keys without hardcoding them.

The challenge? Setting environment variables works differently on Windows (set VAR=value) versus Unix/Mac (VAR=value). This breaks portability.

Accessing Environment Variables

Inside any Node.js script, you read environment variables through process.env:

// In your script file
const apiUrl = process.env.API_URL || 'http://localhost:3000';
console.log(`Connecting to ${apiUrl}`);

Setting Variables in package.json (The Problem)

You might try setting variables directly in your script:

{
  "scripts": {
    "start": "API_URL=https://api.example.com node server.js"
  }
}

This works on Mac/Linux but fails on Windows.

The Solution: cross-env

Install cross-env to make environment variable setting work everywhere:

npm install --save-dev cross-env

Now update your script:

{
  "scripts": {
    "start": "cross-env API_URL=https://api.example.com node server.js",
    "dev": "cross-env NODE_ENV=development node server.js",
    "prod": "cross-env NODE_ENV=production node server.js"
  }
}

cross-env translates the syntax for whatever OS your teammate uses. Set multiple variables by separating them with spaces.

Key Takeaway: Use cross-env in npm scripts to set environment variables portably across all operating systems, making your process.env values accessible regardless of platform.