Learning objectives
After reading this article you will be able to:
- Compare Express, Fastify, NestJS and Hono on practical criteria
- See the same endpoint, with validation, written in each framework
- Pick the right framework for your project and your team
Express, Fastify, NestJS and Hono solve the same problem: take an HTTP request, run your code and send a response. The difference is how much each one decides for you. Express gives you the minimum and leaves the rest to you; NestJS gives you a whole architecture; Fastify and Hono sit in the middle, with better validation and typing without imposing a folder structure.
To compare them fairly, the four examples in this guide implement the same endpoint: POST /tasks, which requires a non-empty title field, answers 201 with the created task and 400 when the input is invalid. All of them read the port from the PORT variable and listen on 0.0.0.0, as a host expects. If you are still designing the API's resources, start with what a REST API is.
# Test any of the four examples with the same command
curl -i -X POST http://localhost:3000/tasks \
-H "Content-Type: application/json" \
-d '{"title": "Review the deploy"}'Which criteria matter?#
- Learning curve. How much you need to learn before the first route works. Express and Hono fit in an afternoon; NestJS asks you to understand modules, decorators and dependency injection.
- Performance. The overhead the framework adds to each request. It matters for high-traffic APIs with small responses. In a typical API, the database and outbound calls usually cost more than the framework.
- Typing and validation. Whether the framework validates input and derives TypeScript types from the same definition, or you glue libraries together for that.
- Ecosystem. Middleware, plugins, examples and ready answers when something breaks.
- Team structure. In a one-person API, freedom helps. With several people in the same codebase, conventions the framework enforces keep every module from being organized a different way.
All four run on an active LTS release of Node.js and work with any database. Picking the database is a separate decision, covered in the best database for Node.js.
When should you choose Express?#
Express describes itself as minimalist and unopinionated: routing, middleware and response helpers, and that's it. It is the Node.js framework with the most tutorials and ready-made middleware (authentication, CORS, uploads, rate limiting). An error thrown in an async handler, or a rejected promise, goes straight to the error handler; older code needed .catch(next) for that.
npm install express, file server.mjs:
import express from "express";
const app = express();
app.use(express.json());
app.post("/tasks", (req, res) => {
const title = req.body?.title;
if (typeof title !== "string" || title.length === 0) {
return res.status(400).json({ error: "title is required" });
}
res.status(201).json({ id: crypto.randomUUID(), title });
});
const port = Number(process.env.PORT) || 3000;
app.listen(port, "0.0.0.0", (error) => {
if (error) throw error;
console.log(`API listening on port ${port}`);
});express.json() parses the JSON body. Without a JSON body, req.body is undefined, hence the ?.. Validation is manual: a real project would add a library such as Zod or Joi.
Pros: small API that is easy to learn; the largest collection of middleware and examples; a large share of Node.js tutorials use Express.
Cons: no input validation or API docs; TypeScript types come from a separate package (@types/express); project layout is entirely up to you, which in a team turns into a different pattern per person.
When should you choose Fastify?#
Fastify was engineered to add as little as possible on top of Node.js, and in the benchmarks the project publishes it comes out ahead of Express. Day to day, its strength is the schema: you describe the request body in JSON Schema, Fastify validates the input with Ajv and answers 400 on its own when it doesn't match. A response schema also speeds up serialization.
npm install fastify, file server.mjs:
import Fastify from "fastify";
const app = Fastify({ logger: true });
const createTaskSchema = {
body: {
type: "object",
required: ["title"],
properties: { title: { type: "string", minLength: 1 } },
},
};
app.post("/tasks", { schema: createTaskSchema }, async (request, reply) => {
reply.code(201);
return { id: crypto.randomUUID(), title: request.body.title };
});
await app.listen({ port: Number(process.env.PORT) || 3000, host: "0.0.0.0" });Note the host: "0.0.0.0". By default, Fastify listens only on localhost, and its own docs recommend 0.0.0.0 in containers. Without it, the process starts but no outside connection gets through, which usually shows up as a 502 after the deploy. logger: true turns on Pino, the logger that ships with Fastify.
Pros: schema-based validation and serialization; built-in structured logs; plugins with encapsulation, where each register creates its own scope; official type providers (TypeBox, Zod and json-schema-to-ts) that turn the schema into TypeScript types.
Cons: less material than Express; encapsulation is confusing at first (what you register inside a plugin is not visible outside it); Express-style middleware does not work out of the box and needs a plugin such as @fastify/express or @fastify/middie.
When should you choose NestJS?#
NestJS does not compete with the other three at the same level: it is an architecture on top of them. It uses Express by default and can switch to Fastify with an official adapter. What it adds is organization, openly inspired by Angular: modules, controllers, providers and dependency injection, all with decorators and TypeScript. The nest new command creates a project with that structure, tests and scripts in place.
In a project created with nest new, the dependencies and the tsconfig.json (with experimentalDecorators and emitDecoratorMetadata) are already set up; for validation, add npm install class-validator class-transformer. The example below fits in src/main.ts, but in a real project each class lives in its own file:
import { Body, Controller, Module, Post, ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { IsNotEmpty, IsString } from "class-validator";
import { randomUUID } from "node:crypto";
class CreateTaskDto {
@IsString()
@IsNotEmpty()
title!: string;
}
@Controller("tasks")
class TasksController {
@Post()
create(@Body() dto: CreateTaskDto) {
return { id: randomUUID(), title: dto.title };
}
}
@Module({ controllers: [TasksController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(process.env.PORT ?? 3000, "0.0.0.0");
}
bootstrap();ValidationPipe uses the parameter's type (CreateTaskDto), which TypeScript records in the decorator metadata, to apply the class-validator rules: invalid input gets a 400, and a POST answers 201 by default. In projects with decorators, compiling with tsc before running is a common path; nest new already ships nest build, which produces the dist/ folder.
Pros: a standard structure that anyone who knows NestJS recognizes; dependency injection that makes testing easier; official modules for GraphQL, WebSockets and microservices; TypeScript end to end.
Cons: a lot of concepts and code for a small API; decorators and dependency injection hide the flow, which weighs on beginners.
When should you choose Hono?#
Hono is small, has zero dependencies and uses only Web Standards (Request, Response, fetch). That is why the same code runs on Node.js, Deno, Bun and edge runtimes, changing only the adapter. On Node.js, that adapter is the @hono/node-server package.
npm install hono @hono/node-server, file server.mjs:
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { validator } from "hono/validator";
const app = new Hono();
app.post(
"/tasks",
validator("json", (value, c) => {
const title = value?.title;
if (typeof title !== "string" || title.length === 0) {
return c.json({ error: "title is required" }, 400);
}
return { title };
}),
(c) => {
const { title } = c.req.valid("json");
return c.json({ id: crypto.randomUUID(), title }, 201);
},
);
serve({
fetch: app.fetch,
port: Number(process.env.PORT) || 3000,
hostname: "0.0.0.0",
});The built-in validator receives the parsed body and can return an error response; whatever it returns reaches the handler through c.req.valid("json"), with the type inferred in TypeScript. Without the Content-Type: application/json header, the body is not parsed and the validator gets an empty object, which here becomes a 400. With Zod, the @hono/zod-validator middleware does the same from a schema.
Pros: lightweight with no dependencies; strong typing and the RPC feature, which shares the route specification between server and client; the same code serves Node.js and the edge.
Cons: a smaller ecosystem than Express; middleware written for Express does not fit; on Node.js you depend on the adapter, and part of the docs' examples assume other runtimes.
How do the four compare side by side?#
| Criterion | Express | Fastify | NestJS | Hono |
|---|---|---|---|---|
| Learning curve | low | medium | high | low |
| Built-in validation | no (separate library) | JSON Schema with Ajv | class-validator through pipes | built-in validator, optional Zod |
| TypeScript | types in a separate package | official type providers | native | native |
| Enforced structure | none | plugins and scopes | modules and dependency injection | none |
| Ecosystem | the largest | large, with official plugins | official modules | smaller |
| Built on Web Standards | no | no | no | yes |
In any of them, TypeScript can run directly through a runner or be compiled first with tsc. The trade-offs of each path are in the best way to run TypeScript in production.
On performance, be wary of loose numbers. Fastify's benchmarks measure minimal routes that return a small JSON object, on a single instance, and the page itself warns that the figures are illustrative: real results depend on hardware, Node.js version and workload. If your API spends most of its time waiting on the database, switching frameworks changes little; tuning the instance's RAM and CPU and the queries changes more.
Which one should you choose for each scenario?#
| Scenario | Recommendation |
|---|---|
| First API, learning Node.js | Express |
| New TypeScript API, small or medium | Fastify or Hono |
| High traffic with small JSON responses | Fastify |
| Large team, long-lived project, strict conventions | NestJS |
| Same code on Node.js and edge runtimes | Hono |
| Existing Express API that works well | Keep it; migrate only for a concrete reason |
When in doubt, pick what the team already knows, not the benchmark winner. All four can run a production API, and most of the work (database, authentication, business rules) is the same in any of them. If the language itself is still open, first compare the best backend language. Once you choose, the next step is to host the Node.js app and go through the API production checklist.
How to do this on Square Cloud#
On Square Cloud, this guide's JavaScript examples (Express, Fastify and Hono) use the Node.js runtime. You upload the project as a ZIP in the dashboard, or deploy with the CLI, GitHub or the VS Code extension, and on start the platform runs npm install when there is no node_modules, with NODE_ENV=production: devDependencies are not installed. The squarecloud.app file is optional, since the dashboard generates it at deploy time with the main file and the memory.
For TypeScript, the TypeScript runtime runs the .ts file itself with tsx, with no dist/ folder and no tsc --build, and installs the package.json dependencies on the server; the runtime page lists NestJS and Hono. There is no build step: if you prefer to compile with tsc, do it in CI (with GitHub Actions, for example) and upload the output, or put the compilation in the start command, with typescript in dependencies.
A web app listens on 0.0.0.0 on the port from the PORT variable, which the platform sets: that is why the examples read process.env.PORT and why Fastify gets an explicit host. It uses at least 512 MB of the plan's RAM, and Hobby starts at R$12.49 per month with 1 GB shared across your apps. Automatic restart, on by default for dashboard deploys, brings back a process that exits with an error. See the details of Node.js hosting.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Is Express still worth using?
Yes. It is the Node.js framework with the most material and middleware, and it forwards errors from async handlers to the error handler. What it does not ship is validation, typing and structure: those choices are yours.
Is Fastify faster than Express?
In the benchmarks Fastify publishes, yes, on minimal routes that return a small JSON object. In a real API, the database and outbound calls usually cost more than the framework, so measure with your own routes before switching.
Does NestJS replace Express?
No: NestJS organizes the app into modules, controllers and providers with dependency injection and, underneath, uses Express by default. An official adapter swaps Express for Fastify.
Is Hono for Node.js or only for the edge?
Both. Hono is built on Web Standards and runs on Node.js through the @hono/node-server adapter, as well as on Deno, Bun and edge runtimes.
Which Node.js framework is best for beginners?
Express, thanks to the number of tutorials and its small API. If you already use TypeScript, Fastify or Hono are good starting points: better validation and types without imposing an architecture.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- CORS error (blocked by CORS policy): cause and fixA CORS error means the API did not allow your page's origin. Learn the causes, how to fix it in Express and FastAPI, and how to test the preflight with curl.