# Config and secrets

- Published: 2026-11-14
- Updated: 2026-11-26
- Tags: Effect on the Backend, Effect, TypeScript
- URL: https://devtrillo.com/writing/effect-backend-7-config-and-secrets/

> Part 7 of a series that builds one backend server on Node with Effect 4. The code is in [devtrillo/effect-on-the-backend](https://github.com/devtrillo/effect-on-the-backend/tree/part-7), and this part is the `part-7` tag.

The server has listened on 3000 since [part 3](/writing/effect-backend-3-a-node-server-in-20-lines/), because the number is typed into `main.ts`. Set `PORT=8080` and it still takes 3000. Part 9 adds Postgres, and the connection URL has a password in it, which is worse than a port: it's the one value that must never end up in a log line.

In a plain Node server you'd write `Number(process.env.PORT ?? 3000)` and move on. `PORT=eighty` gives `NaN`, and `listen` throws `ERR_SOCKET_BAD_PORT`, which is the lucky case. `PORT=""` gives `0`, and Node listens on a random free port without a word; I got 52170. The database URL gets read wherever the pool is created, which may be the first query, minutes after the deploy looked healthy.

This part reads both from the environment with Effect's `Config`, once, before the server listens.

## A config is an effect

`Config.Port("PORT")` describes a value: read `PORT`, parse it as a number between 1 and 65535. It's also an `Effect<number, ConfigError>`, so you can `yield*` it, and nothing is read until something runs it.[^config] `Config.withDefault` covers the case where the variable isn't set:

```ts title="src/main.ts (excerpt)"
const port = Config.Port("PORT").pipe(Config.withDefault(3000))
const databaseUrl = Config.Redacted("DATABASE_URL")
```

`NodeHttpServer` has a variant that takes its options as config instead of values, so the hard-coded port goes away without any reading code of mine:

```ts title="src/main.ts (excerpt)"
const Server = HttpRouter.serve(Layer.mergeAll(Health, ApiRoutes, HttpApiScalar.layer(Api))).pipe(
  Layer.provide(Users.layer),
  Layer.provide(NodeHttpServer.layerConfig(createServer, { port })),
  Layer.provide(LogConfig),
)
```

`layerConfig` reads `port` while the layer builds, which is before `Listening on` and before any request. A bad value fails the layer, and `runMain` logs the `ConfigError` and exits with code 1.

## The secret stays a Redacted

`Config.Redacted` reads a string and wraps it in a `Redacted<string>`. `String()`, `JSON.stringify`, `console.log` and Effect's logger all print `<redacted>`. To get the string out you call `Redacted.value`, which is easy to search for in review.

Nothing connects to the database until part 9, so for now the server reads `DATABASE_URL` in one place: a layer that logs the config it started with. That's a line I want in every server's startup output anyway, and it's the line most likely to leak a password:

```ts title="src/main.ts (excerpt)"
const LogConfig = Layer.effectDiscard(
  Effect.flatMap(Config.all({ port, databaseUrl }), (config) => Effect.log("Config", config)),
)
```

```text title="npm start"
[12:06:09.608] INFO (#2): Config { port: 3000, databaseUrl: <redacted> }
[12:06:09.640] INFO (#2): Listening on http://[::]:3000
```

`DATABASE_URL` has no default on purpose. A server without its database shouldn't come up looking healthy. `LogConfig` is provided last, so it builds first, and a missing URL stops startup before the port is opened. Here's what each environment did at the `part-6` tag and at `part-7`:

**One environment, and what the server did at startup in part 6 and in part 7.**

| Environment | Part 6 | Part 7 |
| --- | --- | --- |
| `DATABASE_URL from .env, no PORT` | Listening on http://[::]:3000 | Config { port: 3000, databaseUrl: <redacted> }, then Listening on http://[::]:3000 |
| `PORT=8080` | Listening on http://[::]:3000. PORT is ignored. | Config { port: 8080, databaseUrl: <redacted> }, then Listening on http://[::]:8080 |
| `PORT=""` | Listening on http://[::]:3000 | Config { port: 3000, databaseUrl: <redacted> }. An empty variable counts as unset, so the default applies. |
| `PORT=eighty` | Listening on http://[::]:3000 | ERROR ConfigError: Expected a string representing a finite number at ["PORT"]. Exit 1, never listens. |
| `PORT=70000` | Listening on http://[::]:3000 | ERROR ConfigError: Expected a value between 1 and 65535 at ["PORT"]. Exit 1. |
| `No DATABASE_URL` | Listening on http://[::]:3000 | ERROR ConfigError: Expected string at ["DATABASE_URL"]. Exit 1. DATABASE_URL="" does the same. |

`PORT=""` is the surprising one. Effect's env provider treats an empty variable as unset, so the default applies. `PORT=eighty` doesn't fall back to 3000: `withDefault` only covers a missing value, and I want it that way, because a typo should stop the deploy.

## Read it at startup, not in a handler

Because a config is an effect, it also works inside a handler, and it compiles. `src/part-7/gotchas.ts` has a route that yields `databaseUrl` per request, run with `HttpRouter.toWebHandler` and no `DATABASE_URL`:

```text title="node src/part-7/gotchas.ts (excerpt)"
handler, unset   500 ""
handler, set     500 ""
```

The server starts fine and `/health` says ok. Every request to the route is an empty 500, and the `ConfigError` is logged at INFO next to `http.status: 500`, the same place part 3's undeclared errors went.

The second line is the stranger one. The script sets `process.env.DATABASE_URL` between the two requests, and the route still fails. The default `ConfigProvider` is built from a copy of `process.env` the first time anything reads config, and Effect caches it for the life of the process.[^cache] Reading config per request doesn't buy you live reloading. It moves the failure from startup to the first request that needs the value.

**Quiz:** You remove the LogConfig layer from main.ts and start the server with no DATABASE_URL. What happens?

- Startup fails with a ConfigError for DATABASE_URL
- The server starts and listens on 3000
- tsc fails, because databaseUrl is declared but unused

**Answer:** The server starts and listens on 3000 — A Config is a description until something yields it. Declaring databaseUrl checks nothing; part 9's database layer is what will read it for real.

- Not "Startup fails with a ConfigError for DATABASE_URL": Only config something runs gets read. Without LogConfig, nothing in part 7 runs databaseUrl.
- Not "tsc fails, because databaseUrl is declared but unused": tsc only complains about unused locals with noUnusedLocals, which this repo doesn't set.

## Where the values come from

`Config` reads from whatever `ConfigProvider` is in context, and the default is `ConfigProvider.fromEnv()`. To load a `.env` file I used Node instead of Effect: `npm start` is now `node --env-file-if-exists=.env src/main.ts`, and the repo has a `.env.example` with a fake URL. A variable already set in the shell wins over the file. Effect has `ConfigProvider.fromDotEnv` too, but it needs a `FileSystem` service, and Node does this with a flag.

The provider matters most in tests. `ConfigProvider.fromUnknown` takes a plain object, so a test never touches `process.env`:

```ts title="src/part-7/gotchas.ts (excerpt)"
const config = await Effect.runPromise(
  Config.all({ port, databaseUrl }).pipe(
    Effect.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ PORT: "8080", DATABASE_URL: "postgres://test" }))),
  ),
)
```

```text
fromUnknown      { port: 8080, databaseUrl: <redacted> }
```

## What the types tell you

`src/part-7/types.ts` is type-check only. Without its `@ts-expect-error` lines:

```text title="npm run check (without the expect-error lines, trimmed)"
error TS2322: Type 'Redacted<string>' is not assignable to type 'string'.
error TS2375: Type 'Layer<Generator | HttpPlatform | HttpServer | NodeServices, ConfigError | ServeError, never>' is not assignable to type 'Layer<HttpServer, ServeError, never>'
  Type 'ConfigError | ServeError' is not assignable to type 'ServeError'.
```

The first is the reason to use `Config.Redacted` over `Config.String` for a secret. Code that wants the password as a string has to call `Redacted.value`, so the compiler points at every place the secret leaves its box. The second is `layerConfig`'s error channel. Part 3's server layer could only fail with `ServeError`; now `ConfigError` is in the type too, and it stays there up to `Layer.launch`, which is where `runMain` turns it into exit code 1.

## The gotchas, and when not to bother

```text title="node src/part-7/gotchas.ts (excerpt)"
both missing     SchemaError(Expected string
  at ["API_KEY"])
not postgres     SchemaError(Expected a string starting with "postgres://"
  at ["DATABASE_URL"])
template         connecting to postgres://app:hunter2@db/app
```

- **A missing variable says `Expected string`.** No "missing" or "not set". The path is right, so you learn to read it as "unset".
- **`Config.all` stops at the first one.** With `API_KEY` and `DATABASE_URL` both unset, you hear about `API_KEY`, fix it, restart, and then hear about the other.
- **Errors don't print the value**, even when the check fails on it. The wrong `postgres://` prefix above came from a URL with `hunter2` in it, and `hunter2` isn't in the message.
- **`Redacted.value` hands back a plain string.** Put it in a template literal and it's in your log. Unwrap it at the one call that needs the string, and nowhere else.

When not to bother: a value that never changes between environments isn't config. The `/openapi.json` path and the `Users` seed stay in code. And if you only have one setting and no secrets, `Config.Port("PORT")` with a default is the whole lesson; you don't need a startup log or a `.env` file for it.

## Run it

```sh
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-7
npm install
cp .env.example .env
npm start
```

Then try `PORT=8080 npm start`, and `PORT=eighty npm start` for the exit. `src/part-7/` has the gotchas script and the type errors.

`main.ts` now has three `Layer.provide` calls in a row, and `LogConfig` only fails fast because it's the last one.

Next in the series: wiring a real app with layers.

[^config]: `Config.ts` at the [`effect@4.0.5`](https://github.com/Effect-TS/effect/blob/effect@4.0.5/packages/effect/src/Config.ts) tag: the `Config` interface ("Configs are also Effects, so they can be yielded"), `Port`, `Redacted` and `withDefault`. `NodeHttpServer.layerConfig` is in `@effect/platform-node`'s `NodeHttpServer.ts` at the same version.

[^cache]: `ConfigProvider.ConfigProvider` is a `Context.Reference` with `defaultValue: () => fromEnv()`, and `fromEnv` spreads `process.env` into a new object. `Context.ts` stores the default value on the reference after the first call.

- **Part 8 — Wiring a real app with layers**: Each dependency is provided where it's used, the config check runs first because it's a dependency, and a layer is shared by reference.
