Load Settings From the Environment

In the last lesson, you created a key for your provider and put a spending limit on the account. Your script needs that key for every request, and the quickest move is to paste it into the code as a string. That copy then travels with the file into commits, shared folders, and chats with colleagues, and anyone who reads it can spend your money.

In this lesson, you’ll keep the key and the script’s other settings in a file that stays on your machine, load them when Node.js starts, and stop the script at once when one is missing or malformed. Start by getting a value into the script without writing it into the code.

Load Settings With --env-file

A setting that changes from one machine to another, or that must stay secret, belongs outside the code. Every running Node.js program has a set of environment variables, names and text values it receives from whatever started it, and your code reads them from process.env. The script for the tea importer’s inbox needs three of them: which provider to call, that provider’s key, and the most output tokens a call may generate, reasoning included.

Typing those into the terminal before every run would be tedious, and one typo causes an error. Instead, Node.js can load them from a file named .env. Your project folder for this course comes with a template, .env.example, that lists every name with an empty value. If you’re building the folder yourself, create .env.example with these lines:

Language: Text Filename: .env.example
MODEL_PROVIDER=
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
MAX_OUTPUT_TOKENS=

Each line is NAME=value. Copy the template to a new file named .env in the same folder:

Language: Windows PowerShell
PS> Copy-Item .env.example .env
Language: Shell
$ cp .env.example .env

Before you fill it in, write a small script that shows what arrives in process.env:

Language: JavaScript Filename: show-settings.js
console.log({
  provider: process.env.MODEL_PROVIDER,
  limit: process.env.MAX_OUTPUT_TOKENS,
});

Run it from the project folder as usual:

Language: Shell
$ node show-settings.js
{ provider: undefined, limit: undefined }

Both values are undefined, and they’d stay that way with a filled-in .env, because Node.js doesn’t read .env on its own. It reads the file when you start it with the --env-file flag. Now open .env in your editor, fill in your provider, your key, and a limit of 400 tokens, and run the script with the flag. Open the version for your provider:

Set MODEL_PROVIDER to openai, paste your key after OPENAI_API_KEY=, and leave ANTHROPIC_API_KEY empty:

Language: Text Filename: .env
MODEL_PROVIDER=openai
OPENAI_API_KEY=paste-your-key-here
ANTHROPIC_API_KEY=
MAX_OUTPUT_TOKENS=400

Then run the script with --env-file=.env:

Language: Shell
$ node --env-file=.env show-settings.js
{ provider: 'openai', limit: '400' }

Set MODEL_PROVIDER to anthropic, paste your key after ANTHROPIC_API_KEY=, and leave OPENAI_API_KEY empty:

Language: Text Filename: .env
MODEL_PROVIDER=anthropic
OPENAI_API_KEY=
ANTHROPIC_API_KEY=paste-your-key-here
MAX_OUTPUT_TOKENS=400

Then run the script with --env-file=.env:

Language: Shell
$ node --env-file=.env show-settings.js
{ provider: 'anthropic', limit: '400' }

This time both values arrive. Look closely at the limit. The quotes around '400' show that it’s a string. Every value in process.env is a string or undefined, so you still have to convert a number from .env before your code can use it as one. Code can also load the file itself with process.loadEnvFile(), but this course uses the flag.

Check Every Setting at Startup

A forgotten flag, an empty line, or a mistyped number in .env doesn’t fail where you made it. The script would still run and get an error back from the provider, possibly halfway through a batch of emails. These problems are easier to fix when the script reads every setting once, at startup, and stops with a message naming the variable.

That’s the job of a settings module. Create a folder named model in the project folder and a file named settings.js inside it. This course keeps every piece of code that names a provider in model/, so a provider change touches nothing else, and this module names both:

Language: JavaScript Filename: model/settings.js
function read(name, fallback) {
  const value = process.env[name] || fallback;
  if (value === undefined) {
    throw new Error(`${name} is missing: add it to .env`);
  }
  return value;
}

const provider = read("MODEL_PROVIDER");
if (provider !== "openai" && provider !== "anthropic") {
  throw new Error(`MODEL_PROVIDER can't be "${provider}"`);
}

const limit = Number(read("MAX_OUTPUT_TOKENS", "300"));
if (!Number.isInteger(limit) || limit < 1) {
  throw new Error(
    "MAX_OUTPUT_TOKENS must be a positive whole number"
  );
}

export const settings = {
  provider,
  apiKey: read(`${provider.toUpperCase()}_API_KEY`),
  maxOutputTokens: limit,
};

The read() function returns a variable’s value or, when the variable is missing, the fallback you pass. With no fallback, a missing variable stops the module with an error.

The function uses || rather than ?? because a line like MAX_OUTPUT_TOKENS=, copied empty from the template, arrives as "", and ?? would keep that empty string.

Below it, each setting gets the treatment it needs:

  • MODEL_PROVIDER has no default, because no choice suits everyone, and it must be one of the two providers the course supports.
  • MAX_OUTPUT_TOKENS falls back to 300, goes through Number(), and must come out as a positive whole number.
  • The key has no default either, since a secret never has one. Its variable name combines the provider’s name in capitals with _API_KEY. You filled in that variable in .env.

The module checks that the provider and token limit are valid and the key is nonempty, but only the provider can tell whether a key works. A mistyped key, the placeholder paste-your-key-here, or a revoked key passes, and the first call fails with a 401 error.

The rest of the script imports settings and never touches process.env again. Replace show-settings.js with a version that imports it:

Language: JavaScript Filename: show-settings.js
import { settings } from "./model/settings.js";

console.log("Output limit:", settings.maxOutputTokens);

The script prints only the limit on purpose. Logging the whole settings object would put your key in the terminal and in any log or bug report, so never log it. Run the script with the flag, and the limit arrives as a number:

Language: Shell
$ node --env-file=.env show-settings.js
Output limit: 400

Now see what the check does with a wrong value. Try a common slip, writing the unit into .env. Change only the last line of your .env to this, and leave your key as it is:

Language: Text
MAX_OUTPUT_TOKENS=400 tokens

When you run the script again, Number() turns "400 tokens" into NaN, so the module stops before anything else happens, and the message names the variable to fix:

Language: Shell
$ node --env-file=.env show-settings.js
...
Error: MAX_OUTPUT_TOKENS must be a positive whole number
    ...

Put the line back to MAX_OUTPUT_TOKENS=400 before you go on. Other values, such as 4e2 or 400.5, are less clear-cut. The button below opens a mentor chat with a question already typed in, so you can trace values like these through read(), Number(), and the check:

A value can come from three places, and they have an order. A variable already set in the shell wins, because --env-file never overwrites one. Otherwise, Node.js loads the value from .env. The code’s fallback applies when the resulting value is missing or empty. You can see the first rule by setting the limit in the shell for one run:

Language: Windows PowerShell
PS> $env:MAX_OUTPUT_TOKENS = "150"
PS> node --env-file=.env show-settings.js
Output limit: 150
PS> Remove-Item Env:MAX_OUTPUT_TOKENS
Language: Shell
$ MAX_OUTPUT_TOKENS=150 node --env-file=.env show-settings.js
Output limit: 150

The shell’s 150 beat the 400 in .env. On Windows, the last command removes the variable again, since PowerShell keeps it for the rest of the session. That order is useful on a server, where the same variables come from the host’s settings instead of a file, and model/settings.js reads them the same way.

The same order applies to your key. If your shell already sets your provider’s key variable, perhaps from trying a provider’s software development kit (SDK), that key wins over the one in .env, and its account may not have your spending limit. To check, open a new terminal and print the variable:

Run echo $OPENAI_API_KEY, or $env:OPENAI_API_KEY in PowerShell. Use ANTHROPIC_API_KEY instead for Anthropic.

If it prints a key, remove the line that sets it from your shell profile, such as ~/.zshrc, or on Windows delete the variable setx created under Edit environment variables for your account. Then open a new terminal, as an open one keeps the old value.

Keep the Key Out of Git

The .env file now holds a real key, so you must never commit it. If your project is a Git repository, or will become one, add .env to the .gitignore file in the project folder before you stage anything with git add:

Language: Text Filename: .gitignore
node_modules/
.env

A .gitignore entry only stops Git from picking up files it isn’t tracking yet. If .env was already staged, it stays staged, and your next commit still includes it. Run git status, and if .env appears under the changes to be committed, take it out of Git’s index while keeping the file on your disk:

Language: Shell
$ git rm --cached .env
rm '.env'

The .env.example file is the one you do commit. It has every name and no values, so anyone who clones the project, including you on another computer, knows which variables to set. When you add a setting, add its name there too.

Once a key is in a commit, deleting the file later doesn’t remove it, because every clone and fork keeps the old commit. Revoke that key on your provider’s key page right away and create a new one.

Your spending limit can reduce the damage but doesn’t guarantee a maximum, since a limit that only sends alerts lets requests carry on, and even an enforced one takes a moment to stop them. If you’d like a refresher on commits and .gitignore, the course Track Your Project With Git covers them.

Worried a key has already slipped into a commit?

Check Your Understanding

The first question uses this lesson’s model/settings.js. Answer them before you open the answers:

  1. Your .env has the line MAX_OUTPUT_TOKENS=, with nothing after the =. What does node --env-file=.env show-settings.js print, first with nothing set in the shell, then with MAX_OUTPUT_TOKENS=150 set there?
  2. Someone deletes a .env file that was committed last week and contains a real key, adds .env to .gitignore, and pushes. Is the key safe?
  1. First, the script prints Output limit: 300: the empty value arrives as "", so || moves on to the fallback, "300", and Number() turns it into 300. Then it prints Output limit: 150: --env-file never overwrites a variable the shell already set, so the fallback isn’t needed.
  2. No. The old commit still holds the key, and anyone with a copy of the repository can read it. Revoke the key, create a new one, and put the new one only in .env.

Your script now reads its settings from the environment and checks them at startup. In the next exercise, Load the Model Settings, you’ll get the tea importer’s reply script ready to start, so it stops before touching a single email when a setting is missing or unusable. It’s the course’s first coding exercise. You’ll edit the code in your browser and click Run Tests to check it, and the exercise’s Contents tab explains how that works.

Become a Member to join the conversation.