Express.js

Also known as: Express

On this page 7

Express.js is a minimal, unopinionated web framework for Node.js that maps incoming HTTP requests to handler functions through routing and a chain of middleware. In web architecture, it typically forms the backend layer of an application: it receives requests from browsers, mobile apps or other services, applies cross-cutting logic such as authentication and parsing, and returns HTML, JSON or files.

Commonly called simply Express, the framework adds only a thin layer over the built-in `http` module, so developers choose their own database, template engine and project structure. That flexibility made it the de facto standard server framework in the Node.js ecosystem and the “E” in the MERN stack.

How Express.js processes a request

Express processes every request by passing it through an ordered pipeline of middleware functions until one of them sends a response. Each middleware receives three arguments: the request object (req), the response object (res) and a `next` callback that hands control to the following function in the chain.

The application object, created with express(), registers middleware with app.use() and route handlers with methods such as app.get() or app.post(). Registration order matters: middleware runs in the order it is declared, so a body parser must appear before any route that reads req.body. When a function calls next(err) with an argument, Express skips ordinary middleware and jumps to error-handling middleware, which is recognized by its four-argument signature (err, req, res, next).

The following table summarizes the core building blocks and the role each plays in the request cycle.

ComponentTypical APIRole in the request cycle
Applicationexpress()Holds settings, middleware stack and routes
Routerexpress.Router()Groups related routes into a mountable module
Middlewareapp.use(fn)Inspects or modifies the request, then calls next
Route handlerapp.get(path, fn)Matches method and path, sends the response
Error handler(err, req, res, next)Formats failures into consistent responses
Static middlewareexpress.static(dir)Serves files such as images and stylesheets
Core components of an Express application

Routing, parameters and middleware types

Express routing matches each request on HTTP method and URL path, and it extracts dynamic segments into req.params. A path such as /users/:id captures the identifier, while query strings appear in req.query. Routers can be mounted on a path prefix, for example app.use('/api/v1', apiRouter), which keeps large codebases modular and makes API versioning straightforward.

Middleware falls into several categories depending on where it is attached and who maintains it. Understanding these categories helps teams decide what belongs in shared infrastructure and what belongs in a single route.

CategoryScopeTypical examples
Application-levelEvery request to the appLogging, security headers, CORS
Router-levelRequests under one routerAuthentication for /admin routes
Route-specificA single endpointInput validation for one form
Built-inShipped with Expressexpress.json(), express.static()
Third-partyInstalled from npmHelmet, cors, compression, Morgan
Error-handlingAfter a failureJSON error formatter, error reporter
Middleware categories in Express

Since Express 5, released as stable in 2024, route handlers that return a rejected promise forward the error to error-handling middleware automatically. In Express 4, an unhandled rejection inside an async handler did not reach the error handler unless the developer wrapped it, which was a frequent source of hanging requests.

Express.js compared with other server frameworks

Express occupies the minimalist end of the framework spectrum, which sets it apart from full-stack frameworks that prescribe structure and bundle an ORM, migrations and an admin interface. The comparison below places it next to frameworks that often compete for the same backend role.

FrameworkLanguage and runtimePhilosophyBuilt-in features
Express.jsJavaScript on Node.jsMinimal, unopinionatedRouting, middleware, static files
FastifyJavaScript on Node.jsPerformance, schema-firstValidation, serialization, plugins
NestJSTypeScript on Node.jsOpinionated, modularDependency injection, decorators
DjangoPythonBatteries includedORM, admin, authentication
FlaskPythonMicroframeworkRouting, templating via Jinja
Ruby on RailsRubyConvention over configurationORM, migrations, generators
Express.js and related backend frameworks

Flask is the closest conceptual relative: both are microframeworks that leave architecture decisions to the team. NestJS, by contrast, can run on top of Express as its HTTP adapter, which shows that Express often serves as a foundation for higher-level frameworks rather than as the final abstraction.

Typical uses and configuration choices

Express is most often used to build REST and JSON APIs, backend for frontend services, server-rendered pages with template engines such as Pug or EJS, and lightweight proxies or webhook receivers. Its small core starts quickly and has a modest memory footprint, which suits containers and small virtual machines.

A production deployment needs deliberate configuration, because the defaults favor development convenience. The decision table below lists common situations and the recommended approach.

SituationRecommended choiceReason
App runs behind a load balancerSet trust proxy correctlyClient IP and protocol are read accurately
Public-facing APIAdd Helmet and rate limitingReduces header leaks and abuse
Heavy static assetsServe from a CDN or reverse proxyFrees the event loop for dynamic work
Multi-core serverRun several processes or containersOne Node.js process uses one main thread
Environment-specific settingsSet NODE_ENV=productionEnables view caching and terser errors
Configuration decisions for production Express apps

Following twelve-factor app practice, configuration such as database URLs and secrets should come from environment variables rather than from code, which keeps the same build portable across staging and production.

Limitations and common mistakes

The freedom Express offers is also its main weakness: without conventions, large projects can drift into inconsistent structure, duplicated validation and tangled middleware ordering. Teams usually compensate with an agreed folder layout, a validation library and TypeScript types.

  • Blocking the event loop: CPU-heavy work such as image processing or large JSON parsing stalls every concurrent request; move it to worker threads or a queue.
  • Wrong middleware order: placing authentication after the route it should protect silently leaves the route open.
  • Forgetting to end the response: a handler that neither calls next() nor sends a response leaves the client waiting until a timeout.
  • Leaking stack traces: running without NODE_ENV=production can expose internal error details to clients.
  • Assuming built-in validation: Express does not validate input; unchecked req.body data is a common injection vector.

In raw throughput benchmarks, Express usually trails Fastify because of its older routing and serialization design. For most applications, however, database and network latency dominate response time, so the difference rarely decides the outcome.

The short version

Express.js is a small toolkit that helps a server written in JavaScript answer requests from websites and apps. When someone opens a page or an app asks for data, Express looks at the address, decides which piece of code should respond and sends the answer back.

Think of it as a receptionist with a checklist. Every visitor passes a series of desks, one checks identity, another records the visit, and the last one hands over what was requested. Express provides the desks and the order; the developer decides what each desk does. The key takeaway is that Express stays deliberately simple and lets teams add only the parts they need.

Where it makes a difference

A regional food delivery company runs a React mobile app and needs an API that lists restaurants, accepts orders and receives payment webhooks. A team of three developers builds the backend with Express on Node.js, organizing it into separate routers for /restaurants, /orders and /webhooks, each with its own validation middleware.

Shared middleware handles JSON parsing, token authentication, security headers and request logging. Because the payment webhook needs the raw request body to verify signatures, the team mounts a raw body parser only on that router, something the flexible middleware chain makes simple. The service runs in four containers behind a load balancer with trust proxy enabled.

During a weekend promotion, the API handles about 300 requests per second with median latency near 40 milliseconds, most of it spent in database queries. The outcome is a backend shipped in six weeks that the small team can still read and extend, which was the main reason for choosing a minimal framework.