A Node server in 20 lines

By Esteban Trillo7 min readupdated Effect on the BackendEffectTypeScript

There's no listen() in the file. It runs inside the layer, a few lines after the close it will need.
There's no listen() in the file. It runs inside the layer, a few lines after the close it will need.

Part 3 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-3 tag.

There’s no app.listen() in the server below. I wrote it, it answered on port 3000, and I still went looking for the line that opens the port, because I couldn’t point at it.

In Learning Effect part 9 I ran each Effect at the edge, which meant a runPromise inside every route handler. On a server, that’s one edge per route. This part moves the edge to a single line at the bottom of src/main.ts. It also turns getUser from part 2 into GET /users/:id.

The plain version

Here’s the server without Effect: a health check, one user route, and a signal handler so Ctrl+C closes the server.

src/part-3/plain.ts
import { createServer } from "node:http"
const users = new Map([["1", { id: "1", name: "Ada" }]])
const server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://localhost")
const match = url.pathname.match(/^\/users\/([^/]+)$/)
const user = match && users.get(match[1]!)
if (req.method === "GET" && url.pathname === "/health") {
res.writeHead(200, { "content-type": "text/plain" }).end("ok")
} else if (req.method === "GET" && user) {
res.writeHead(200, { "content-type": "application/json" })
res.end(JSON.stringify(user))
} else {
res.writeHead(404).end()
}
})
server.listen(3000, () => console.log("Listening on http://localhost:3000"))
for (const signal of ["SIGINT", "SIGTERM"]) {
process.on(signal, () => server.close(() => process.exit(0)))
}

That’s 19 lines of code, and it works. It’s also missing things I’d want before shipping it. The id comes straight out of a regex, so /users/%31 is a 404 even though %31 is 1. There’s no request log. server.close() waits for every open connection with no time limit. Start a second copy while the first is running, and Node crashes with Unhandled 'error' event and EADDRINUSE.

The Effect version

src/main.ts
import { NodeHttpServer, NodeRuntime } from "@effect/platform-node"
import { Effect, Layer } from "effect"
import { HttpRouter, HttpServerResponse } from "effect/http"
import { createServer } from "node:http"
import { getUser } from "./getUser.ts"
import { Users } from "./Users.ts"
const Health = HttpRouter.add("GET", "/health", HttpServerResponse.text("ok"))
const GetUser = HttpRouter.add(
"GET",
"/users/:id",
Effect.fn("UsersHttp.get")(function* () {
const { id = "" } = yield* HttpRouter.params
const user = yield* getUser(id)
return HttpServerResponse.jsonUnsafe(user)
}),
)
const Server = HttpRouter.serve(Layer.mergeAll(Health, GetUser)).pipe(
Layer.provide(Users.layer),
Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),
)
Layer.launch(Server).pipe(NodeRuntime.runMain)

That’s 21 lines without the blanks, two more than plain Node. So “20 lines” in the title is a round number, not a win. If you’re hoping Effect saves you lines on a server this small, it doesn’t. The two extra lines buy everything on that list from the last section, and I didn’t write any of it.

Run it with node src/main.ts (or npm start). There’s no build step, because Node strips the types itself:

curl against npm start
GET /health 200 ok
GET /users/1 200 {"id":"1","name":"Ada"}
GET /users/%31 200 {"id":"1","name":"Ada"}
GET /users/1/ 200 {"id":"1","name":"Ada"}
GET /users/2 500
GET /users/ 404
GET /nope 404
POST /users/1 404

The params are decoded, so %31 finds Ada. A trailing slash is ignored. A route that doesn’t match is a 404, and a handler that fails is a 500 with the server still up. Plain Node gave 404 for %31, /users/1/ and /users/2 alike.

The id = "" default is there because HttpRouter.params types every param as string | undefined. That’s all the decoding this part does. Any string reaches getUser, and part 4 puts a Schema in front of it.

Routes are layers

HttpRouter.add takes a method, a path and a handler. The handler can be a plain response, like the health check, an Effect, or a function from the request to an Effect. It doesn’t register anything on some global router. It returns a Layer, the same kind of value Learning Effect part 8 used to provide a service. This one provides nothing. It needs an HttpRouter, and when it’s built, it adds its route to it. Layer.mergeAll puts the two routes together.

The handler is an Effect.fn with a name, the way part 2 said handlers should be. It reads the path params from the route context, calls getUser exactly as part 2 left it, and returns JSON. Users never shows up in the handler’s arguments. It’s in the type, and you’ll see it travel.

jsonUnsafe is the version of HttpServerResponse.json that can’t fail. The safe one returns an Effect that fails if the body won’t serialize, which is a real concern for a BigInt and not one for { id, name }.

The lines at the bottom are where that type gets paid off. Each step removes one thing from the third slot, the requirements (Learning Effect part 7 is about that slot). Step through them:

Pick a step
const GetUser = HttpRouter.add("GET", "/users/:id", …)

const Server = HttpRouter.serve(Layer.mergeAll(Health, GetUser)).pipe(
  Layer.provide(Users.layer),
  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),
)

Layer.launch(Server).pipe(NodeRuntime.runMain)

Step 1 of 6: add

Layer<never, never, HttpRouter | Request<"Requires", Users> | Request<"Error", UserNotFound>>

A route. It needs a router to live in, and it carries two notes about its handler: it needs Users, and it can fail with UserNotFound.

Step 2 of 6: serve

Layer<never, never, Users | HttpServer>

The router is built from the routes. UserNotFound is gone from the type, because a handler failure turns into a 500. Users moved into the third slot, next to the server it now needs.

Step 3 of 6: provide Users

Layer<never, never, HttpServer>

Users is supplied. One requirement left.

Step 4 of 6: provide Node

Layer<never, ServeError, never>

Nothing left to need. ServeError shows up in the error slot, because a port can already be taken.

Step 5 of 6: launch

Effect<never, ServeError, never>

An Effect now. never in the success slot means it never returns a value. It still hasn't run.

Step 6 of 6: runMain

No type to show. This line runs.

This is the only line that does anything. Building the layer calls server.listen, the log says Listening on http://[::]:3000, and the process stays up until a signal interrupts it.

HttpRouter.serve does more than glue. Unless you pass disableLogger, it adds a logging middleware, and unless you pass disableListenLog, it logs the address. That’s where the request log comes from:

npm start (paths trimmed)
INFO (#2): Listening on http://[::]:3000
INFO (#12) http.span=1ms: Sent HTTP response { 'http.method': 'GET', 'http.url': '/health', 'http.status': 200 }
INFO (#13) http.span=1ms: Sent HTTP response { 'http.method': 'GET', 'http.url': '/users/1', 'http.status': 200 }
INFO (#15) http.span=0ms: UserNotFound: user 2 not found
at Object.<anonymous> (src/Users.ts:23:34)
at Users.find (src/getUser.ts:8:23)
at Users.find (definition) (src/Users.ts:19:18)
at getUser (src/main.ts:15:25)
at getUser (definition) (src/getUser.ts:4:31)
at UsersHttp.get (node_modules/effect/dist/internal/effect.js:1055:10)
at UsersHttp.get (definition) (src/main.ts:13:10) { 'http.method': 'GET', 'http.url': '/users/2', 'http.status': 500 }
INFO (#16) http.span=0ms: HttpServerError: RouteNotFound (GET /users/) { 'http.method': 'GET', 'http.url': '/users/', 'http.status': 404 }

The number after INFO is the fiber id. Every request gets a new one: #12, #13, #15. That’s what one runMain instead of one runPromise per handler looks like. There’s one running program, and each request is a fiber inside it. The 500 also has part 2’s trace, with the handler’s name on the bottom two frames.

A missing user should be a 404, not a 500, and it shouldn’t be logged at INFO. Part 6 maps errors to status codes. Today, every failure is a 500.

Which line in src/main.ts is the one where port 3000 actually opens?

Where’s listen()?

It’s inside NodeHttpServer.make, which the layer runs when it’s built. Here’s the part that matters, from the 4.0.5 source:1

@effect/platform-node/src/NodeHttpServer.ts (excerpt)
const scope = yield* Effect.scope
const server = evaluate()
// …
yield* Scope.addFinalizer(scope, shutdown)
yield* Effect.callback<void, ServeError>((resume) => {
// …
server.listen(options, () => {
// …
resume(Effect.void)
})
})

shutdown is server.close(). So the order is: register the close as a finalizer on the current scope, then listen. And Layer.launch is one line in Effect’s source: build the layer inside a scope, then wait forever.2 The scope stays open for as long as the program runs, so the server does too.

The code that closes the server is registered before the port opens, so there’s no window where you have a listening server and nothing that will close it. NodeRuntime.runMain is the part that ends it. It runs the Effect on the main fiber and adds SIGINT and SIGTERM listeners that interrupt that fiber.3 Ctrl+C interrupts the fiber, the scope closes, and the finalizer closes the server. I never wrote a signal handler, and the process exits:

kill -INT, then kill -TERM
exit code 130
exit code 130

Both signals give 130. Effect’s default teardown uses 130 whenever the only cause is an interruption, so SIGTERM doesn’t give you the 143 a shell would. The plain version exits with 0, because I wrote process.exit(0).

Here’s the whole life of the server, in the order it runs:

Startup and shutdown of the Effect serverStartup runs left to right: NodeRuntime.runMain runs the program, Layer.launch builds the server layer inside a scope, NodeHttpServer registers server.close as a finalizer on that scope, and only then calls listen on port 3000. Shutdown is a second chain: SIGINT or SIGTERM makes runMain interrupt the main fiber, the scope closes, the finalizer registered at startup runs server.close, which waits for requests in flight, and the process exits with code 130.runMainNodeRuntimeLayer.launchopens a scopeaddFinalizerregisters closelisten :3000port opensSIGINTor SIGTERMinterruptmain fiberscope closesfinalizerserver.close()exit 130registered before listen
A request is 2 seconds into a 3-second handler when the process gets SIGTERM. What happens?

I tried this in a minimal lab server with a 3-second handler, not on this repo’s code. The slow request finished with a 200, my own finalizer ran after it, and the exit code was 130. The wait has a limit: gracefulShutdownTimeout defaults to 20 seconds. Part 14 goes into shutdown properly.

What the types tell you

runMain only takes an Effect whose third slot is never. If something is still required, it won’t compile. src/part-3/mistakes.ts leaves out each layer in turn:

npm run check (without the expect-error lines)
error TS2684: The 'this' context of type 'Effect<never, never, HttpServer>' is not assignable to method's 'this' of type 'Effect<unknown, unknown, never>'.
Type 'HttpServer' is not assignable to type 'never'.
error TS2684: The 'this' context of type 'Effect<never, ServeError, Users>' is not assignable to method's 'this' of type 'Effect<unknown, unknown, never>'.
Type 'Users' is not assignable to type 'never'.

Forget the Node server and tsc names HttpServer. Forget Users.layer and it names Users, even though the only code that asks for it is getUser, called from inside a handler.

The error slot has ServeError in it because listening can fail. Start a second copy while the first one is running:

node src/main.ts (port already taken, trimmed)
ERROR (#2): ServeError:
at Server.onError (node_modules/@effect/platform-node/dist/NodeHttpServer.js:80:26)
[cause]: Error: listen EADDRINUSE: address already in use :::3000
exit code 1

It’s a typed failure from building the layer, logged at ERROR, with exit code 1. And the never in the success slot of Effect<never, ServeError, never> is the type saying the program has no normal way to finish.

The gotchas, and when not to bother

  • POST to a GET route is a 404, not a 405. The router only knows “no route matched”. POST /users/1 is logged as RouteNotFound (POST /users/1).
  • Call HttpRouter.serve once. Its documentation warns that calling it twice builds your app layer twice. I saw that in the same minimal lab server, not in this repo.
  • It starts slower. On my laptop (one machine, so treat these as rough), the plain server answered its first request about 110 ms after node started. The Effect one took between 390 and 520 ms. That’s module loading, and for a long-running server it doesn’t matter. For a cold-start function with three routes, plain Node is fine, and HttpRouter.toWebHandler exists if you want the router without a Node server.
  • The port is hard-coded. Part 7 reads it from config.

Part 5’s HttpApi is built on this same router, and part 12 is about testing them.

Run it

Terminal window
git clone https://github.com/devtrillo/effect-on-the-backend
cd effect-on-the-backend
git checkout part-3
npm install
npm start

Then curl localhost:3000/users/1 in another terminal. Try /users/%31 and /users/2 as well, and watch the log print a new fiber id for each request. Ctrl+C when you’re done, and check the exit code with echo $?. src/part-3/ has the plain version and the type errors above.

Next in the series: Schema at the boundary, where /users/:id stops accepting any string.

  • Part 4 — Schema at the boundary: /users/:id stops accepting any string, POST /users decodes its JSON body, and bad input becomes a 400 that names the field.

Footnotes

  1. NodeHttpServer.ts at the effect@4.0.5 tag, lines 102–140. The same file defines gracefulShutdownTimeout and ServeError. ↩

  2. Layer.ts at the effect@4.0.5 tag: launch = (self) => scoped(andThen(build(self), never)). The v4 docs site has no HTTP server guide yet; the HttpRouter and NodeHttpServer API pages are the closest. ↩

  3. NodeRuntime.ts at the effect@4.0.5 tag. The exit code comes from Runtime.defaultTeardown in effect/src/Runtime.ts. ↩

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.