Home / Articles

zen.js Compiles the Request Path Before Traffic Arrives

zen.js compiles each route into a pipeline before listen, and one Zod schema drives validation, handler types, response filtering, and OpenAPI. The alpha is not for production.

Publisher: REACTAPP.TOP10 min read2229 words

This article is published in English.

Sources: What If a Node.js Web Framework Compiled Your App Before the First Request?

A Node.js process can already know a lot before it reads a single byte from a socket. Which handler owns the path. Which middleware sits on that path. What has to be checked. How the body should be written back out. That knowledge is in the registration code you already wrote.

The awkward follow-up is obvious. That picture of the call is fixed once registration finishes. Why read it again on every request?

zen.js is a Node.js framework built around that follow-up, and the code is public. Treat the code that registers routes as a tiny language. Compile the application graph while the process is coming up. Then run the pipeline that compilation wrote for this app and for no other app.

Your JavaScript is not being lowered to a native binary. The experiment is narrower. How much bookkeeping that belongs to the framework can be finished before any client connects?

The trouble sits around the route

The abstractions in current web frameworks are already strong. You declare paths, hang middleware on them, state validation rules, write the function that builds a response, and wire up plugins. Those tools are why an application stays possible to build and possible to keep.

Looking up a function and calling it is still a thin slice of an HTTP call.

A normal request moves through stages, and you cannot casually reorder them:

routing, then the parameters, then middleware, then validation, then the handler, then serialization, then the bytes on the wire.

Rules change from one stage to the next. Some of the work is asynchronous. Some of it is a plain function return. Authentication middleware belongs on certain routes and is missing from others. Some responses carry a schema that has to be enforced. Other responses answer to a different set of requirements.

The application definition already holds all of that, and it holds it before listen has accepted a connection.

None of this deletes real runtime work. The framework still has to read the request that actually arrived, run your logic, and do jobs like querying a database.

It does force a split that is worth pinning down.

Which steps truly depend on the request that just arrived, and which steps are structural choices you can freeze once while the process boots?

zen.js is built on that split.

Registration describes the app. Startup compiles it

In zen.js, the calls that register the application are a statement of the behavior you want. They are the description. They are not the interpreter that runs on every call.

While the process starts, the framework assembles an application graph and then freezes it. Routes, chains of middleware, validators, serializers, and the other definitions that affect execution are turned into paths the server can run directly.

The flow is short enough to sketch:

the definition you wrote, then the graph, then compilation, then a pipeline ready for requests.

What the server does next is the whole point. It stops walking the objects you declared at the top of the file. For each route, it runs the pipeline that compilation emitted.

When a route never uses a stage, that stage can be missing from the generated code. There is no leftover branch whose only job is to notice the stage and skip it, request after request.

A route whose handlers are plain synchronous functions can go further. When the contracts for that pipeline allow a sync path, the compiled output can omit the async and await wrapping a mixed route would carry.

Asynchronous work is still handled when it is actually present. A promise is not being disguised as a plain return. The saving is smaller than that: a path should not pay for assumptions it never uses.

The framework emits JavaScript you can open, rather than tucking the result into a runtime you cannot read. You should be able to open what startup wrote and see the trick. A chart in a README, or a line of marketing, is a weaker argument.

A small API in front of the compiler

The calls you type are meant to feel familiar. Pull zen in from the package @erenthedeveloper0/zen.

import { zen } from "@erenthedeveloper0/zen";

From there you construct an app, map GET / to a function that returns a string, and bind port 3000.

const app = zen();app.get("/", () => "Hello world");await app.listen(3000);

The surface stays small on purpose. Register a handler. Hand back a response. Start listening.

A tiny sample is cheap. Other frameworks ship those too. The interesting claim is that those registration calls are the input the compiler consumes.

Writing routes should stay approachable. Under that small API, the machinery is supposed to get more deliberate.

Schemas own the contract

Compiling the graph is only one of the design rules.

The next rule is that a schema has to cover more than the check that greets a request on the way in.

Say the endpoint hands back user rows. The record your application keeps internally can include fields a client must never see.

Leave the usual split in place and four artifacts drift: the docs, the TypeScript types, the filter that shapes responses, and the validation rules. Someone updates one and forgets the others.

zen.js uses the schema as one shared contract. It drives validation, the types your handler sees, serialization of the response, and OpenAPI output.

The sample pulls zen and NotFound from @erenthedeveloper0/zen, and z from Zod.

import { zen, NotFound } from "@erenthedeveloper0/zen";
import { z } from "zod";

User is a Zod object: an integer id, an email, and a name. The route is GET /users/:id<int>. A 200 body has to match User. The handler calls db.users.find with ctx.params.id. If that lookup returns undefined, the handler throws NotFound and the message names the missing id. Otherwise the handler returns the row. Here db stands for the application's database access layer.

const User = z.object({
  id: z.number().int(),
  email: z.email(),
  name: z.string(),
});const app = zen();app.get(
  "/users/:id<int>",
  { response: { 200: User } },
  async (ctx) => {
    const row = await db.users.find(ctx.params.id);    if (row === undefined) {
      throw new NotFound(`User ${ctx.params.id} not found`);
    }    return row;
  },
);await app.listen(3000);

The response schema is the allow-list for a successful body. The database row might also carry passwordHash. The compiled serializer drops that property on the way out, because the contract never listed it.

Because the path marks :id as an integer, ctx.params.id is typed as a number rather than a raw string. The route declaration is what the handler's type rests on.

OpenAPI output is another consumer of that same contract.

These are not four conveniences bolted on beside each other. They follow one rule. Write the meaning of the app down one time. Every other layer should read that, not a private copy that can wander off.

Make the behavior readable

A framework is hard to trust when the behavior that matters hides behind conventions you are expected to memorize. zen.js is not aimed at that kind of framework.

Inspectability is in the design for that reason.

At startup the framework can look for routes that collide. It can name the file and line that registered each colliding route. Once a route has been resolved, it can describe that route's execution chain.

Other tools let you look at the application graph, and let you walk the steps one request actually took.

In the current build, app.graphDocument() dumps the app as canonical JSON. Fingerprints on that dump tell you when the app changed and when a route contract changed.

explainRequest() comes at the same problem from the request side. It records the call after the fact: each step's result, and the time that step spent.

A stack trace is not the only reason those tools exist. You can use them as a check that the running server still does what the design said it would do.

Once startup rewrites the app, you still need to see the thing startup wrote. For a framework organized around compilation, that check belongs with the model. It is not something you add after the fact.

Measure the speed. Do not assume it

Put a compiler in front of the request path and people will ask about speed. Fair.

Can a pipeline built for one route cut the framework's overhead? Can async machinery you do not need, and stages you do not use, disappear from that route? How do the answers change once the application looks like a real service instead of an empty handler?

You can measure those questions. You should not treat them as settled before you have numbers.

A framework benchmark moves for a lot of reasons: work inside the handler, how large the body is, what serialization costs, how connections behave, which runtime you are on, and plenty of other variables. One workload's number does not travel to every other app.

Benchmarks are being written next to zen.js so the questions can be tested. There is no promise that zen.js beats mature frameworks on every workload.

What you want from the numbers is a map. Costs this design drops. Costs it cannot drop. Spots where a trade-off shows up in a real app.

Work that belongs to the application still dominates. If the query to the database is slow, compiling the route leaves it slow.

The point is not to delete runtime work at random. The runtime should perform the work this app really needs, and nothing piled on by unused stages.

That is the speed claim the project is willing to test.

The hard job is staying honest

This layout creates its own trouble.

The cost shows up when the process boots. The compiler has to sort out how configuration, hooks, schemas, routes, middleware, and plugins affect each other. When something fails, the error has to be readable. The pipeline that comes out has to keep the behavior you thought you wrote.

Drop the awkward behavior and a benchmark looks great. Keep that behavior, let the app get large, and predictability is the thing that breaks first.

That is why the project treats several things as load-bearing from the start: diagnostics when two routes collide, contracts the type checker can see, responses that stay correct, lifecycle behavior, and a real test suite. You do not tune the hot path first and bolt these on later. Without them the design is not something a team can live with.

This path is optional. Switch runtimes only when the result fits the programs you are actually shipping. The behavior has to match what you expect, the trade-offs have to be acceptable, and the way you write the app has to stay sane.

The alpha, as it stands

The release you can install today is 0.2.0-alpha.

What exists is a working cut through the design, not a finished server framework. The pipeline for a request is generated code. Responses are shaped by the schema. OpenAPI comes out of those schemas. Routes can report conflicts. You can inspect the application.

You need Node.js 22.6 at a minimum. If the project uses TypeScript, you need TypeScript 5.0 at a minimum. Nothing else is required at runtime by the core package.

The limit on that status is blunt. zen.js is an alpha, and you should not ship it in production. Expect the API to move before 1.0 lands. Several pieces of the larger design are still missing.

It is public this early because the architecture is worth arguing about while people can still push on the design and force changes.

Three places to read:

  • Code repository
  • Design notes
  • Release history

Install the published alpha of @erenthedeveloper0/zen by asking npm for the alpha tag.

npm install @erenthedeveloper0/zen@alpha

The questions that come next

A shorter request path is the obvious thing to hope for. The more interesting bet is a framework where you can account for what ran, where contracts do not quietly diverge, and where behavior at runtime follows the definition you wrote instead of a second, hidden reading of it.

The objections deserve the same time.

Where does compilation pile on more complexity than the design can carry? Which choices during a request are actually worth fixing while the process starts? Which awkward cases would make the design painful to keep alive? What measurements would tell you the direction is worth keeping?

Shipping the code, timing it, and listening when someone pokes a hole in the design will answer those. A prior belief will not.

The repository is public on purpose. If the design is wrong, say where, and be specific.

The code is the place to begin: the repository

Polite comments on whether the API looks pleasant are the least useful thing you can send right now. What helps is a judgment on the model. Does it hold? Where does it fail? Which measurements would talk you into believing frameworks on Node.js should head this way?