Module 03 · Lesson 3.3
Configuration and Secrets
On this page
- What you will learn
- Configuration and secrets in plain words
- Worked scenario: Tidewell's environment files
- A config module that fails early and stays quiet
- What to do if a key is committed
- Step-by-step workflow: set up configuration safely
- What the assistant does and what you do
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Your house key does not belong on a sign outside your front door. Yet every year, developers save passwords and API keys inside their code and push them to a shared site. Bots find them within minutes.
In this lesson you keep Tidewell's settings out of the code. You set up an example file with fake values, make Git ignore the real one and write a small config module that fails with a clear message when something is missing. You also learn what to do if a key is committed by mistake, because sooner or later someone will do it.
What you will learn
- Separate business rules, settings and secrets, and say where each one lives.
- Set up .env.local, .env.example and .gitignore so that no real value is committed.
- Write a config module that names missing settings without printing any values.
- Respond correctly if a key is committed: revoke first, then clean the history.
Before you start
- Completed Repository Structure and Conventions, or have a project with a
src/libfolder. - Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
Configuration and secrets in plain words
Configuration is anything that can differ between your laptop, a test copy and the live site. The database address is a good example. A secret is a setting that lets someone act as you, such as a password or an API key. Think of a secret as the key to the clinic's front door.
- Environment variable
- A named setting that sits outside your code and is handed to the program when it starts, like a dial on the wall that the machine reads.
- API key
- A long secret code that proves to an outside service that a request comes from you. Anyone who has it can spend your allowance.
- .env.local
- A file on your own machine that holds the real values. It is never shared.
- .env.example
- A file that lists the setting names with fake values. It is shared, so a new person knows what to fill in.
- Git ignore
- A list of file patterns that Git promises not to track, so they cannot be saved by accident.
Three kinds of value, three homes
| Kind | Example | Where it lives |
|---|---|---|
| Business rule | A patient may change a booking only 24 hours or more before it starts. | In code, in src/features/bookings/rules.ts, with a comment that points to the decision. |
| Setting that differs by place | The database address, the public web address of the site. | Environment variables: DATABASE_URL, APP_BASE_URL. |
| Secret | The key for the email-sending service, and the database password. | Environment variables, with real values only in .env.local: EMAIL_API_KEY. |
A business rule is not a setting. If the notice period lived in the environment, nobody would review a change to it, and a test could not rely on it. Put rules in code, where they are reviewed. Put places and secrets in the environment. The Twelve-Factor App (opens in a new tab) explains why settings that vary by place stay out of the code.
Worked scenario: Tidewell's environment files
Tidewell needs three variables. DATABASE_URL is the address and login of the database. APP_BASE_URL is the public address of the booking site. EMAIL_API_KEY is a placeholder until Module 6, when the booking system starts to send emails. The example file lists all three, with fake values.
# Fake values only. Copy this file to .env.local and fill in real ones.
DATABASE_URL=postgres://tidewell_user:change-me@localhost:5432/tidewell_booking
APP_BASE_URL=http://localhost:3000
EMAIL_API_KEY=replace-with-your-key-in-module-6Committed to the repository. Every value is fake.
A new developer copies this file to .env.local and replaces the fake values with real ones. The .env.local file stays on their machine. To make sure of that, add this to .gitignore.
# local environment files hold real values
.env*
# the example file holds fake values and is committed
!.env.exampleIgnore every env file, then allow the example file back in.
Tested in a scratch repository with empty .env, .env.local and .env.example files: Git listed only the example file and the ignore file as new.
?? .env.example
?? .gitignoreA config module that fails early and stays quiet
If a setting is missing, you want to know at start-up, not when a patient clicks a button. One file, src/lib/config.ts, reads all settings once and checks them. The rest of the code asks that file. No other file reads the environment directly.
The error message names the missing variables. It must never print their values, because logs are often shared with other people and services. The function takes the environment as an argument, so a test can pass in fake values.
export interface Config {
databaseUrl: string;
appBaseUrl: string;
emailApiKey: string;
}
type Env = Record<string, string | undefined>;
const REQUIRED = ["DATABASE_URL", "APP_BASE_URL", "EMAIL_API_KEY"] as const;
/** Read settings once. Name what is wrong, never print what is set. */
export function loadConfig(env: Env = process.env): Config {
const missing = REQUIRED.filter((name) => !env[name]?.trim());
if (missing.length > 0) {
throw new Error(
`Missing environment variables: ${missing.join(", ")}. Copy .env.example to .env.local and fill them in.`,
);
}
if (!URL.canParse(env.APP_BASE_URL!)) {
throw new Error("APP_BASE_URL is set but is not a valid web address.");
}
return {
databaseUrl: env.DATABASE_URL!,
appBaseUrl: env.APP_BASE_URL!,
emailApiKey: env.EMAIL_API_KEY!,
};
}Tested with the TypeScript compiler. The default argument reads the real environment when the app runs.
What each part does
Configis the shape of the checked settings. The rest of the app gets a typed object, not loose text.REQUIREDlists the three names.as constlets the compiler remember them exactly.missingcollects every name that is absent or only spaces.- If any are missing, the function throws one error that lists all of them. You fix everything in one go.
URL.canParsechecks that the base address is a real web address. The message names the variable only.- If all is well, the function returns the three values under clear names.
import { loadConfig } from "./config";
function attempt(label: string, env: Record<string, string | undefined>) {
try {
const config = loadConfig(env);
console.log(`${label}: ok, base address is ${config.appBaseUrl}`);
} catch (error) {
console.log(`${label}: ${(error as Error).message}`);
}
}
attempt("Nothing set", {});
attempt("Two missing", { DATABASE_URL: "postgres://user:secret-pass@localhost:5432/tidewell" });
attempt("Bad address", {
DATABASE_URL: "postgres://user:secret-pass@localhost:5432/tidewell",
APP_BASE_URL: "not a url",
EMAIL_API_KEY: "fake-key-123",
});
attempt("All set", {
DATABASE_URL: "postgres://user:secret-pass@localhost:5432/tidewell",
APP_BASE_URL: "http://localhost:3000",
EMAIL_API_KEY: "fake-key-123",
});Runs the check four times with fake environments. The database password in the example is fake.
Nothing set: Missing environment variables: DATABASE_URL, APP_BASE_URL, EMAIL_API_KEY. Copy .env.example to .env.local and fill them in.
Two missing: Missing environment variables: APP_BASE_URL, EMAIL_API_KEY. Copy .env.example to .env.local and fill them in.
Bad address: APP_BASE_URL is set but is not a valid web address.
All set: ok, base address is http://localhost:3000Look at the second line. The database address was set and held a fake password, but the message does not show it. It only lists what is still missing. Run twice, the output was identical.
What to do if a key is committed
It happens to everyone. A real key lands in a commit. The first rule is to treat that key as public from now on, even if the repository is private and even if you delete the file a minute later. Git remembers every commit, and anyone with access, or any copy someone made, can read the old one.
Step 1: Revoke and replace the key first
Sign in to the service that issued the key. Disable it and create a new one. Put the new value in
.env.local. This is called rotating a key. Do this before anything else, because cleaning Git history takes time and a copy may already exist.What you should see: The old key no longer works.
Step 2: Check for misuse
Look at the service's usage page for requests you do not recognise. Tell the person who owns the account. For a database password, check who could have connected.
What you should see: You know whether the key was used by anyone else.
Step 3: Remove the secret from the code
Replace it with a read from the environment, add the file to
.gitignoreand commit the fix.What you should see: The current files no longer hold the secret.
Step 4: Clean the history if it was shared
Use a history-rewriting tool such as git filter-repo or the BFG Repo-Cleaner, following its own documentation. Everyone who has a copy must then fetch the cleaned history. If the commit was never shared, a local reset may be enough.
What you should see: The old commit no longer contains the key.
Step 5: Turn on scanning
Many hosting sites can scan pushes for known key formats. Read about GitHub secret scanning (opens in a new tab) and enable the equivalent on your host.
What you should see: A future mistake is flagged soon after it is pushed.
Step-by-step workflow: set up configuration safely
Step 1: List every setting the app needs
For each one, decide: business rule, setting that differs by place, or secret. Rules go in code.
What you should see: A short table of names and kinds.
Step 2: Ignore env files before you create one
Edit
.gitignorefirst. Then check that Git ignores a test.env.localfile.What you should see:
git statusdoes not list.env.local.Step 3: Write .env.example with fake values
One line per setting, with a harmless value and a comment. Commit it.
What you should see: A new person can see what to fill in.
Step 4: Add the config module
Read and check settings in one file. Make it list missing names without printing values.
What you should see: A clear error at start-up when something is wrong.
Step 5: Search for stray secrets
Search the code for keys, passwords and addresses. Check that no other file reads the environment directly.
What you should see: Only
config.tstouches the environment.Step 6: Test from a clean clone
Clone the repository elsewhere, copy
.env.exampleto.env.localand start the project. Fix any step that fails.What you should see: The README steps are enough to run the project.
- .env.example
Fake values, committed
- .env.local
Real values, ignored
- Environment
Handed to the program
- config.ts
Read once and checked
- Typed object
Used by the app
Real values never pass through the repository.
What the assistant does and what you do
| Task | Assistant's part | Your part |
|---|---|---|
| Writing .env.example | Drafts the names and fake values. | Check that every value is fake and the names match the real settings. |
| Writing config.ts | Drafts the checks and the error messages. | Check that no message prints a value, and that no default is a real address or key. |
| Finding stray secrets | Can search code and list suspects. | Verify each find and rotate any real key. |
| Handling a leak | Explains the steps. | Revoke the key yourself in the service. No tool can do it for you. |
| Seeing your real values | It should never need them. | Never paste .env.local or real keys into a chat. |
Conclusion and your next step
Keep rules in code, places and secrets in the environment, and real values in a file Git ignores. A config module fails early and names what is missing without showing values. If a key is committed, revoke and replace it first, then clean the history.
Your next step: now that settings are safe, add automatic checks that catch mistakes before review. Continue with Linting, Formatting and Type Checks.
For more on keeping keys safe, read Managing API Keys Locally. To see how a similar project handles secrets, try the Appointment Booking Portal.
Reusable prompt
Configuration plan without real values
Gets an assistant to plan settings, an example file and a config check, without ever seeing a real secret.
You are helping me set up configuration for a web app. Never ask for real keys or passwords. Use fake placeholder values only.
Project: tidewell-booking (fictional clinic booking app). Next.js and TypeScript.
Settings:
- DATABASE_URL: address and login of the PostgreSQL database (secret).
- APP_BASE_URL: public web address of the site.
- EMAIL_API_KEY: key for an email service. Placeholder until a later module (secret).
Business rule, not a setting: online changes are allowed only 24 hours or more before an appointment. It lives in code.
Tasks:
1. Write a .env.example with one line per setting, a fake value and a short comment.
2. Write the lines to add to .gitignore so that env files are ignored but .env.example is not.
3. Describe, in words only, a config module that reads all settings once, lists missing names in one error and never prints a value. Say what it should do for a malformed web address.
4. List the ways a secret could end up in the browser, in this stack, and how to avoid each.
5. Warn me about any default value you would be tempted to add, and say why it is risky.Show the reusable template
Replace each {{placeholder}} with your own details.
You are helping me set up configuration for a web app. Never ask for real keys or passwords. Use fake placeholder values only.
Project: {{project_name}} ({{stack}}).
Settings:
{{settings_with_kind}}
Business rules, not settings: {{business_rules}}
Tasks:
1. Write a .env.example with one line per setting, a fake value and a short comment.
2. Write the lines to add to .gitignore so that env files are ignored but .env.example is not.
3. Describe, in words only, a config module that reads all settings once, lists missing names in one error and never prints a value. Say what it should do for a malformed value.
4. List the ways a secret could end up in the browser, in this stack, and how to avoid each.
5. Warn me about any default value you would be tempted to add, and say why it is risky.Expected output and limitations
An example env file with fake values and comments, the ignore lines, a plain-words description of the config module, a list of ways a secret can reach the browser, and a warning about risky defaults.
.env.example
DATABASE_URL=postgres://user:change-me@localhost:5432/tidewell # fake
APP_BASE_URL=http://localhost:3000
EMAIL_API_KEY=replace-with-your-key # placeholder
.gitignore
.env*
!.env.example
Browser exposure: a variable name that starts with NEXT_PUBLIC_; a secret passed as a prop
from a server file into a client component; a secret returned in an error message.
Risky default: falling back to a local database address if DATABASE_URL is missing.
That would hide a setup mistake and may point the app at the wrong database.Limitations to keep in mind
- The assistant may offer real-looking values. Check that every value is clearly fake.
- It may be out of date on how the framework treats env files. Check the framework's own docs.
- It cannot know which of your settings are secret unless you say. Label each one.
Common errors and how to fix them
A real key appears in a commit, a log or a chat.
Why it happens: It was pasted to get something working, or a file was not ignored.
Fix: Revoke and replace the key first. Then remove it from the code, clean the history if it was shared, and turn on scanning.
The app starts, then fails later with a strange database error.
Why it happens: A setting was missing or wrong, and nothing checked it at start-up.
Fix: Read and check every setting in config.ts when the app starts, and make it name each missing setting.
A secret is visible in the browser's page source.
Why it happens: The variable name starts with NEXT_PUBLIC_, or a client component received it.
Fix: Remove the prefix, keep the use on the server and rotate the key, because it has been public.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Configuration for Ferngate Cycle Repairs
Ferngate's parts tracker needs a database, a public address and, later, a supplier ordering key. Sort its settings into business rules, place settings and secrets. Write the example file and the ignore lines. Then describe what the config module should do when something is missing.
You will need
- Settings to sort: database address and password, public web address, supplier ordering key, low-stock threshold, shop opening hours.
- Ferngate's facts: the low-stock threshold is 'to be agreed', and the connection is unreliable.
- The three-column table from this lesson.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Ask whether the value would differ between a laptop and the live site. If not, it may be a rule.
- The first leak step is about the key itself, not about Git.
Show a model answer
A strong answer treats the database address and web address as place settings, the database password and supplier key as secrets, and the low-stock threshold as a business rule that the owner has not decided yet. Opening hours are likely a rule or content, not an environment value. The example file uses obviously fake values, and the ignore lines use a pattern that allows the example. The config description lists all missing names at once, and the leak note says to revoke and replace the supplier key first, then check its use, then clean history.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: C. Once pushed, the key may already be copied, and only revoking it stops it working. Deleting the file leaves it in history. Rewriting history is a needed second step, but it does not undo a leak by itself, which is why it is the tempting wrong first move.
Show the answer and explanation
Answer: B. It is a business rule, so it should be reviewed and tested like code. An environment file is tempting because it is easy to change, but a change there skips review. The example file is committed, and it is for setting names and fake values.
Show the answer and explanation
Answer: A. Names tell you what to fix. Printing values leaks secrets into logs, which is why the second option is wrong even though it feels helpful. An empty message hides the problem from the person who needs to fix it.
Frequently asked questions
What is an environment variable?
It is a named setting that lives outside your code and is handed to the program when it starts. It works like a dial on the wall that the machine reads. Because it is outside the code, the same code can run with different settings in different places.
Should I commit my .env file to Git?
No. A file with real values must stay on your machine and be listed in .gitignore. Commit a .env.example file instead, with fake values, so others can see which settings to fill in.
What do I do if I accidentally commit an API key?
Treat the key as public. Revoke it in the service and create a new one first. Then remove it from the code, clean the Git history if the commit was shared and check the service for use you do not recognise.
Is it safe to paste my .env file into an AI assistant?
No. Anything you paste may be stored or seen by others, depending on the tool and its settings. Share only setting names and fake values. If you pasted a real key, revoke it and replace it.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- How to use environment variables in Next.js(opens in a new tab)
Next.js · Official documentation · How env files are loaded and which variables reach the browser.
- The Twelve-Factor App: Config(opens in a new tab)
12factor.net · The reasoning for keeping place-specific settings out of the code.
- Secrets Management - OWASP Cheat Sheet Series(opens in a new tab)
OWASP · Official documentation · Practical guidance on storing, rotating and auditing secrets.
- Secret scanning - GitHub Docs(opens in a new tab)
GitHub · Official documentation · How a code host can flag a key that was pushed by mistake.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.