Part 7 of a series that builds one backend server on Node with Effect 4. The code is in devtrillo/effect-on-the-backend, and this part is the
part-7tag.
The server has listened on 3000 since part 3, 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.1 Config.withDefault covers the case where the variable isn’t set:
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:
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:
const LogConfig = Layer.effectDiscard( Effect.flatMap(Config.all({ port, databaseUrl }), (config) => Effect.log("Config", config)),)[12:06:09.608] INFO (#2): Config { port: 3000, databaseUrl: <redacted> }[12:06:09.640] INFO (#2): Listening on http://[::]:3000DATABASE_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:
- Part 6
- Listening on http://[::]:3000
- Part 7
- Config { port: 3000, databaseUrl: <redacted> }, then Listening on http://[::]:3000
- Part 6
- Listening on http://[::]:3000. PORT is ignored.
- Part 7
- Config { port: 8080, databaseUrl: <redacted> }, then Listening on http://[::]:8080
- Part 6
- Listening on http://[::]:3000
- Part 7
- Config { port: 3000, databaseUrl: <redacted> }. An empty variable counts as unset, so the default applies.
- Part 6
- Listening on http://[::]:3000
- Part 7
- ERROR ConfigError: Expected a string representing a finite number at ["PORT"]. Exit 1, never listens.
- Part 6
- Listening on http://[::]:3000
- Part 7
- ERROR ConfigError: Expected a value between 1 and 65535 at ["PORT"]. Exit 1.
- Part 6
- Listening on http://[::]:3000
- Part 7
- 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:
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.2 Reading config per request doesn’t buy you live reloading. It moves the failure from startup to the first request that needs the value.
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:
const config = await Effect.runPromise( Config.all({ port, databaseUrl }).pipe( Effect.provide(ConfigProvider.layer(ConfigProvider.fromUnknown({ PORT: "8080", DATABASE_URL: "postgres://test" }))), ),)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:
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
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.allstops at the first one. WithAPI_KEYandDATABASE_URLboth unset, you hear aboutAPI_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 withhunter2in it, andhunter2isn’t in the message. Redacted.valuehands 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
git clone https://github.com/devtrillo/effect-on-the-backendcd effect-on-the-backendgit checkout part-7npm installcp .env.example .envnpm startThen 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.
- 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.
Footnotes
-
Config.tsat theeffect@4.0.5tag: theConfiginterface (“Configs are also Effects, so they can be yielded”),Port,RedactedandwithDefault.NodeHttpServer.layerConfigis in@effect/platform-node’sNodeHttpServer.tsat the same version. ↩ -
ConfigProvider.ConfigProvideris aContext.ReferencewithdefaultValue: () => fromEnv(), andfromEnvspreadsprocess.envinto a new object.Context.tsstores the default value on the reference after the first call. ↩

