Skip to content

These are the docs of abedmurrar/express, an unofficial fork of Express. The official Express docs are at expressjs.com. What the fork changes is in the Fork section.

Application Object ​

The app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module:

js
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('hello world');
});

app.listen(3000);
js
import express from 'express';

const app = express();

app.get('/', function (req, res) {
  res.send('hello world');
});

app.listen(3000);
ts
import express, { type Express, type Request, type Response } from 'express';

const app: Express = express();

app.get('/', function (req: Request, res: Response) {
  res.send('hello world');
});

app.listen(3000);

The app object has methods for

It also has settings (properties) that affect how the application behaves; for more information, see Application settings.

INFO

The Express application object can be referred from the request object and the response object as req.app, and res.app, respectively.

Properties ​

app.locals ​

Type: Object

The app.locals object has properties that are local variables within the application, and will be available in templates rendered with res.render.

WARNING

The locals object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.

js
console.dir(app.locals.title);
// => 'My App'

console.dir(app.locals.email);
// => 'me@myapp.com'

Once set, the value of app.locals properties persist throughout the life of the application, in contrast with res.locals properties that are valid only for the lifetime of the request.

You can access local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in middleware via req.app.locals (see req.app)

js
app.locals.title = 'My App';
app.locals.strftime = require('strftime');
app.locals.email = 'me@myapp.com';

app.mountpath ​

Type: String | String[]

The app.mountpath property contains one or more path patterns on which a sub-app was mounted.

INFO

A sub-app is an instance of express that may be used for handling the request to a route.

js
const express = require('express');

const app = express(); // the main app
const admin = express(); // the sub app

admin.get('/', (req, res) => {
  console.log(admin.mountpath); // /admin
  res.send('Admin Homepage');
});

app.use('/admin', admin); // mount the sub app
js
import express from 'express';

const app = express(); // the main app
const admin = express(); // the sub app

admin.get('/', (req, res) => {
  console.log(admin.mountpath); // /admin
  res.send('Admin Homepage');
});

app.use('/admin', admin); // mount the sub app
ts
import express, { type Express, type Request, type Response } from 'express';

const app: Express = express(); // the main app
const admin: Express = express(); // the sub app

admin.get('/', (req: Request, res: Response) => {
  console.log(admin.mountpath); // /admin
  res.send('Admin Homepage');
});

app.use('/admin', admin); // mount the sub app

It is similar to the baseUrl property of the req object, except req.baseUrl returns the matched URL path, instead of the matched patterns.

If a sub-app is mounted on multiple path patterns, app.mountpath returns the list of patterns it is mounted on, as shown in the following example.

js
const admin = express();

admin.get('/', (req, res) => {
  console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ]
  res.send('Admin Homepage');
});

const secret = express();
secret.get('/', (req, res) => {
  console.log(secret.mountpath); // /secr{*splat}t
  res.send('Admin Secret');
});

admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app
app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app
ts
import express, { type Express, type Request, type Response } from 'express';

const admin: Express = express();

admin.get('/', (req: Request, res: Response) => {
  console.log(admin.mountpath); // [ '/adm{*splat}n', '/manager' ]
  res.send('Admin Homepage');
});

const secret: Express = express();
secret.get('/', (req: Request, res: Response) => {
  console.log(secret.mountpath); // /secr{*splat}t
  res.send('Admin Secret');
});

admin.use('/secr{*splat}t', secret); // load the 'secret' router on '/secr{*splat}t', on the 'admin' sub app
app.use(['/adm{*splat}n', '/manager'], admin); // load the 'admin' router on '/adm{*splat}n' and '/manager', on the parent app

app.router ​

Type: Router

The application's in-built instance of router. This is created lazily, on first access.

js
const express = require('express');
const app = express();
const router = app.router;

router.get('/', (req, res) => {
  res.send('hello world');
});

app.listen(3000);
js
import express from 'express';

const app = express();
const router = app.router;

router.get('/', (req, res) => {
  res.send('hello world');
});

app.listen(3000);
ts
import express, { type Express, type Request, type Response } from 'express';

const app: Express = express();
const router = app.router;

router.get('/', (req: Request, res: Response) => {
  res.send('hello world');
});

app.listen(3000);

You can add middleware and HTTP method routes to the router just like an application.

For more information, see Router.

Events ​

app.on('mount') ​

Parameters

  • callback · Function

    The listener called when the mount event fires. It receives the parent app as its only argument: callback(parent).

The mount event is fired on a sub-app, when it is mounted on a parent app. The parent app is passed to the callback function.

INFO

Sub-apps will:

  • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  • Inherit the value of settings with no default value.
  • Inherit case sensitive routing and strict routing unless those settings are explicitly set on the sub-app. These values configure the sub-app's router when it is created; mounting does not reconfigure an existing router. If a parent uses path-specific middleware to protect a sub-app, apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it.

For details, see Application settings.

js
const admin = express();

admin.on('mount', (parent) => {
  console.log('Admin Mounted');
  console.log(parent); // refers to the parent app
});

admin.get('/', (req, res) => {
  res.send('Admin Homepage');
});

app.use('/admin', admin);
ts
import express, { type Express, type Application, type Request, type Response } from 'express';

const admin: Express = express();

admin.on('mount', (parent: Application) => {
  console.log('Admin Mounted');
  console.log(parent); // refers to the parent app
});

admin.get('/', (req: Request, res: Response) => {
  res.send('Admin Homepage');
});

app.use('/admin', admin);

Methods ​

app.all() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

This method is like the standard app.METHOD() methods, except it matches all HTTP verbs.

Examples ​

The following callback is executed for requests to /secret whether using GET, POST, PUT, DELETE, or any other HTTP request method:

js
app.all('/secret', (req, res, next) => {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.all('/secret', (req: Request, res: Response, next: NextFunction) => {
  console.log('Accessing the secret section ...');
  next(); // pass control to the next handler
});

The app.all() method is useful for mapping "global" logic for specific path prefixes or arbitrary matches. For example, if you put the following at the top of all other route definitions, it requires that all routes from that point on require authentication, and automatically load a user. Keep in mind that these callbacks do not have to act as end-points: loadUser can perform a task, then call next() to continue matching subsequent routes.

js
app.all('{*splat}', requireAuthentication, loadUser);

Or the equivalent:

js
app.all('{*splat}', requireAuthentication);
app.all('{*splat}', loadUser);

Another example is white-listed "global" functionality. The example is similar to the ones above, but it only restricts paths that start with "/api":

js
app.all('/api/{*splat}', requireAuthentication);

app.delete() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes HTTP DELETE requests to the specified path with the specified callback functions. For more information, see the routing guide.

Example ​

js
app.delete('/', (req, res) => {
  res.send('DELETE request to homepage');
});
ts
import { type Request, type Response } from 'express';

app.delete('/', (req: Request, res: Response) => {
  res.send('DELETE request to homepage');
});

app.disable() ​

Parameters

  • name · String

    The name of the Boolean setting to disable; one of the properties from the app settings table.

Returns: Application

Sets the Boolean setting name to false, where name is one of the properties from the app settings table. Calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').

For example:

js
app.disable('trust proxy');
app.get('trust proxy');
// => false

app.disabled() ​

Parameters

  • name · String

    The name of the Boolean setting to test; one of the properties from the app settings table.

Returns: Boolean

Returns true if the Boolean setting name is disabled (false), where name is one of the properties from the app settings table.

js
app.disabled('trust proxy');
// => true

app.enable('trust proxy');
app.disabled('trust proxy');
// => false

app.enable() ​

Parameters

  • name · String

    The name of the Boolean setting to enable; one of the properties from the app settings table.

Returns: Application

Sets the Boolean setting name to true, where name is one of the properties from the app settings table. Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo').

js
app.enable('trust proxy');
app.get('trust proxy');
// => true

app.enabled() ​

Parameters

  • name · String

    The name of the setting to test; one of the properties from the app settings table.

Returns: Boolean

Returns true if the setting name is enabled (true), where name is one of the properties from the app settings table.

js
app.enabled('trust proxy');
// => false

app.enable('trust proxy');
app.enabled('trust proxy');
// => true

app.engine() ​

Parameters

  • ext · String

    The file extension the template engine is registered for (for example, pug or html).

  • callback · Function

    The template engine function used to render files with the given extension.

Returns: Application

Registers the given template engine callback as ext.

By default, Express will require() the engine based on the file extension. For example, if you try to render a "foo.pug" file, Express invokes the following internally, and caches the require() on subsequent calls to increase performance.

js
app.engine('pug', require('pug').__express);

Use this method for engines that do not provide .__express out of the box, or if you wish to "map" a different extension to the template engine.

For example, to map the EJS template engine to ".html" files:

js
app.engine('html', require('ejs').renderFile);

In this case, EJS provides a .renderFile() method with the same signature that Express expects: (path, options, callback), though note that it aliases this method as ejs.__express internally so if you're using ".ejs" extensions you don't need to do anything.

The extension of a view matches a registered engine whatever its case: an engine registered as HTML renders user.html, and one registered as html renders page.HTML. An engine registered in the same case wins. File names keep their case, so with app.set('view engine', 'Html'), res.render('page') looks for page.Html. Express 5.3.0 matched the case exactly and tried require() for any other case.

Some template engines do not follow this convention. The consolidate.js library maps Node template engines to follow this convention, so they work seamlessly with Express.

js
const engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
js
import engines from 'consolidate';

app.engine('haml', engines.haml);
app.engine('html', engines.hogan);

Several template engines ​

This is a fork addition; Express 5.3.0 has no view engines setting.

Without it, a view name with no extension uses the view engine extension, and res.render('page') throws "No default engine was specified" when view engine is not set, whatever engines are registered. To render views of several engines by name alone, list their extensions in the view engines setting:

js
app.engine('pug', require('pug').__express);
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'pug');
app.set('view engines', ['html', 'ejs']);

app.render('page', callback); // page.pug, else page.html, else page.ejs

A name without a known extension then tries these extensions, in this order, and renders the first file found:

  1. the view engine extension, when set: an app that renders a file today renders the same one;
  2. each extension in view engines, in the order listed (with or without the leading dot; one already tried is skipped).

Each extension is tried in every views folder, in order, before the next extension, so the view engine file in the second folder wins over a view engines file in the first. A folder's index file counts for its extension, as with view engine.

An extension is known when an engine is registered for it (in any case), or when it is the view engine extension or one in view engines (in any case). A name with a known extension is looked up as before. Any other extension is part of the name: with app.set('view engines', ['pug']), res.render('user.profile') renders user.profile.pug, where Express 5.3.0 tries to load a profile module.

The engine of the file found is the registered one, matched in any case, or else the module named after the extension, loaded with require(), as for view engine. Only the found file's engine is loaded.

When no file is found, the error lists the extensions tried, in order:

Failed to lookup view "page" in views directory "/app/views" with extension ".pug", ".html" or ".ejs"

With the view cache setting on, the file found is cached under the view name, so adding a file for an earlier extension later has no effect until restart. A failed lookup is not cached. Sub-apps inherit view engines and the parent's engines, but not views, which has a default.

app.get(name) ​

Parameters

  • name · String

    The name of the setting to read; one of the strings in the app settings table.

Returns: any

Returns the value of name app setting, where name is one of the strings in the app settings table. For example:

js
app.get('title');
// => undefined

app.set('title', 'My Site');
app.get('title');
// => 'My Site'

app.get() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes HTTP GET requests to the specified path with the specified callback functions.

For more information, see the routing guide.

Example ​

js
app.get('/', (req, res) => {
  res.send('GET request to homepage');
});
ts
import { type Request, type Response } from 'express';

app.get('/', (req: Request, res: Response) => {
  res.send('GET request to homepage');
});

app.listen() ​

Parameters

  • port · Number · optional

    The TCP port to listen on. If omitted or 0, the OS assigns an arbitrary unused port.

  • host · String · optional

    The host on which to accept connections.

  • backlog · Number · optional

    The maximum length of the queue of pending connections.

  • path · String · optional

    The path of a UNIX socket to listen on, as an alternative to host and port.

  • callback · Function · optional

    A function called once the server is listening. If the server fails to start listening (for example with EADDRINUSE), the error is passed to this callback as its argument. Errors after the server is listening are not: they go to the server's own error listeners, as on a server made with http.createServer(). (Express 5.3.0 left its listener attached, so the first later error was silently dropped.)

Returns: http.Server

Binds and listens for connections on the specified host and port, or starts a UNIX socket and listens for connections on the given path. This method is identical to Node's http.Server.listen().

If port is omitted or is 0, the operating system will assign an arbitrary unused port, which is useful for cases like automated tasks (tests, etc.).

js
const express = require('express');
const app = express();

app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket
js
import express from 'express';

const app = express();

app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket
ts
import express, { type Express } from 'express';

const app: Express = express();

app.listen(3000); // bind and listen on a TCP port
app.listen('/tmp/sock'); // or listen on a UNIX socket

INFO

When the server emits an error event (such as EADDRINUSE), the error is passed to the provided callback. Handle it inside the callback:

js
const server = app.listen(8080, '0.0.0.0', (error) => {
  if (error) {
    throw error; // e.g. EADDRINUSE
  }
  console.log(`Listening on ${JSON.stringify(server.address())}`);
});

The app returned by express() is in fact a JavaScript Function, designed to be passed to Node's HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app with the same code base, as the app does not inherit from these (it is simply a callback):

js
const express = require('express');
const https = require('https');
const http = require('http');
const app = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
js
import express from 'express';
import https from 'https';
import http from 'http';

const app = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
ts
import express, { type Express } from 'express';
import https from 'https';
import http from 'http';

const app: Express = express();

http.createServer(app).listen(80);
https.createServer(options, app).listen(443);

The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:

js
app.listen = function () {
  const server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

INFO

All the forms of Node's http.Server.listen() method are in fact actually supported.

app.METHOD() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are app.get(), app.post(), app.put(), and so on. See Routing methods below for the complete list.

String route patterns match the whole request path. For example, app.get('/apple', ...) matches /apple, but not /apple/images. With the same path, app.use() matches both.

Regular expressions can match part of the path. app.get(/apple/, ...) matches /apple/images. Use ^ and $ for a full match: app.get(/^\/apple$/, ...) matches only /apple.

Routing methods ​

Express supports the following routing methods corresponding to the HTTP methods of the same names:

  • checkout
  • copy
  • delete
  • get
  • head
  • lock
  • merge
  • mkactivity
  • mkcol
  • move
  • m-search
  • notify
  • options
  • patch
  • post
  • purge
  • put
  • query
  • report
  • search
  • subscribe
  • trace
  • unlock
  • unsubscribe

The API documentation has explicit entries only for the most popular HTTP methods app.get(), app.post(), app.put(), app.delete(), and app.query(). However, the other methods listed above work in exactly the same way.

To route methods that translate to invalid JavaScript variable names, use the bracket notation. For example, app['m-search']('/', function ....

js
app.get('/', (req, res) => {
  res.send('GET request to homepage');
});

app.post('/', (req, res) => {
  res.send('POST request to homepage');
});

// methods that are invalid JavaScript variable names use bracket notation
app['m-search']('/', (req, res) => { 
  res.send('M-SEARCH request to homepage');
});
ts
import { type Request, type Response } from 'express';

app.get('/', (req: Request, res: Response) => {
  res.send('GET request to homepage');
});

app.post('/', (req: Request, res: Response) => {
  res.send('POST request to homepage');
});

// methods that are invalid JavaScript variable names use bracket notation
app['m-search']('/', (req: Request, res: Response) => {
  res.send('M-SEARCH request to homepage');
});

INFO

The app.get() function is automatically called for the HTTP HEAD method in addition to the GET method if app.head() was not called for the path before app.get().

The method, app.all(), is not derived from any HTTP method and loads middleware at the specified path for all HTTP request methods. For more information, see app.all.

For more information on routing, see the routing guide.

app.param() ​

Parameters

  • name · String | String[]

    The name of the route parameter, or an array of names.

  • callback · Function

    The trigger called as callback(req, res, next, value, name): the request object, the response object, the next middleware, the value of the parameter, and the name of the parameter, in that order.

Add callback triggers to route parameters, where name is the name of the parameter or an array of them, and callback is the callback function. The parameters of the callback function are the request object, the response object, the next middleware, the value of the parameter and the name of the parameter, in that order.

If name is an array, the callback trigger is registered for each parameter declared in it, in the order in which they are declared. Furthermore, for each declared parameter except the last one, a call to next inside the callback will call the callback for the next declared parameter. For the last parameter, a call to next will call the next middleware in place for the route currently being processed, just like it would if name were just a string.

For example, when :user is present in a route path, you may map user loading logic to automatically provide req.user to the route, or perform validations on the parameter input.

js
app.param('user', (req, res, next, id) => {
  // try to get the user details from the User model and attach it to the request object
  User.find(id, (err, user) => {
    if (err) {
      next(err);
    } else if (user) {
      req.user = user;
      next();
    } else {
      next(new Error('failed to load user'));
    }
  });
});

Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers, nor are they triggered for route parameters inherited from parent routers. Hence, param callbacks defined on app will be triggered only by route parameters defined on app routes.

All param callbacks will be called before any handler of any route in which the param occurs, and they will each be called only once in a request-response cycle, even if the parameter is matched in multiple routes, as shown in the following examples.

js
app.param('id', (req, res, next, id) => {
  console.log('CALLED ONLY ONCE');
  next();
});

app.get('/user/:id', (req, res, next) => {
  console.log('although this matches');
  next();
});

app.get('/user/:id', (req, res) => {
  console.log('and this matches too');
  res.end();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.param('id', (req: Request, res: Response, next: NextFunction, id: string) => {
  console.log('CALLED ONLY ONCE');
  next();
});

app.get('/user/:id', (req: Request, res: Response, next: NextFunction) => {
  console.log('although this matches');
  next();
});

app.get('/user/:id', (req: Request, res: Response) => {
  console.log('and this matches too');
  res.end();
});

On GET /user/42, the following is printed:

CALLED ONLY ONCE
although this matches
and this matches too
js
app.param(['id', 'page'], (req, res, next, value) => {
  console.log('CALLED ONLY ONCE with', value);
  next();
});

app.get('/user/:id/:page', (req, res, next) => {
  console.log('although this matches');
  next();
});

app.get('/user/:id/:page', (req, res) => {
  console.log('and this matches too');
  res.end();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.param(['id', 'page'], (req: Request, res: Response, next: NextFunction, value: string) => {
  console.log('CALLED ONLY ONCE with', value);
  next();
});

app.get('/user/:id/:page', (req: Request, res: Response, next: NextFunction) => {
  console.log('although this matches');
  next();
});

app.get('/user/:id/:page', (req: Request, res: Response) => {
  console.log('and this matches too');
  res.end();
});

On GET /user/42/3, the following is printed:

CALLED ONLY ONCE with 42
CALLED ONLY ONCE with 3
although this matches
and this matches too

app.path() ​

Returns: String

Returns the canonical path of the app, a string.

js
const app = express();
const blog = express();
const blogAdmin = express();

app.use('/blog', blog);
blog.use('/admin', blogAdmin);

console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'
ts
import express, { type Express } from 'express';

const app: Express = express();
const blog: Express = express();
const blogAdmin: Express = express();

app.use('/blog', blog);
blog.use('/admin', blogAdmin);

console.log(app.path()); // ''
console.log(blog.path()); // '/blog'
console.log(blogAdmin.path()); // '/blog/admin'

The behavior of this method can become very complicated in complex cases of mounted apps: it is usually better to use req.baseUrl to get the canonical path of the app.

app.post() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes HTTP POST requests to the specified path with the specified callback functions. For more information, see the routing guide.

Example ​

js
app.post('/', (req, res) => {
  res.send('POST request to homepage');
});
ts
import { type Request, type Response } from 'express';

app.post('/', (req: Request, res: Response) => {
  res.send('POST request to homepage');
});

app.put() ​

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes HTTP PUT requests to the specified path with the specified callback functions.

Example ​

js
app.put('/', (req, res) => {
  res.send('PUT request to homepage');
});
ts
import { type Request, type Response } from 'express';

app.put('/', (req: Request, res: Response) => {
  res.send('PUT request to homepage');
});

app.query() ​

Requires: Node.js >=20.19.3 <21 || >=22.2.0

Parameters

  • path · String | RegExp | Array

    The path to match for this route: a string, a regular expression, or an array of either. String patterns match the whole request path. See Path examples for syntax.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Routes HTTP QUERY requests to the specified path with the specified callback functions. For more information, see the routing guide.

DANGER

The HTTP QUERY method was standardized on June 15, 2026 as RFC 10008. Client and intermediary support is still limited. Verify that your target environments support the QUERY verb before relying on it in production.

The HTTP QUERY method (RFC 10008) is designed for queries whose input is too large or too sensitive to encode in the URL. Unlike GET, a QUERY request carries a body containing the query input. Unlike POST, it is explicitly safe and idempotent, intermediaries and caches can retry it automatically, and the response is cacheable (with the request body included in the cache key).

Use app.query() when query parameters would exceed URL length limits, contain sensitive data that should not appear in server logs or browser history, or are too complex to express cleanly as a URL query string, such as deeply nested filters or structured criteria.

Because the query input travels in the request body, req.body is undefined until you mount a body-parsing middleware such as express.json() or express.urlencoded() that matches the request's Content-Type.

Example ​

js
app.use(express.json()); // populate req.body for application/json payloads

app.query('/search', (req, res) => {
  // complex filter criteria arrive in req.body, not the URL
  const results = db.search(req.body);
  res.json(results);
});
ts
import express, { type Request, type Response } from 'express';

app.use(express.json()); // populate req.body for application/json payloads

app.query('/search', (req: Request, res: Response) => {
  // complex filter criteria arrive in req.body, not the URL
  const results = db.search(req.body);
  res.json(results);
});

app.render() ​

Parameters

  • view · String

    The name of the view to render.

  • locals · Object · optional

    An object whose properties define local variables for the view.

  • callback · Function

    The callback invoked as callback(err, html) with the rendered HTML.

Returns the rendered HTML of a view via the callback function. It accepts an optional parameter that is an object containing local variables for the view. It is like res.render(), except it cannot send the rendered view to the client on its own.

INFO

Think of app.render() as a utility function for generating rendered view strings. Internally res.render() uses app.render() to render views.

WARNING

The view argument performs file system operations like reading a file from disk and evaluating Node.js modules, and as so for security reasons should not contain input from the end-user.

WARNING

The locals object is used by view engines to render a response. The object keys may be particularly sensitive and should not contain user-controlled input, as it may affect the operation of the view engine or provide a path to cross-site scripting. Consult the documentation for the used view engine for additional considerations.

DANGER

The local variable cache is reserved for enabling view cache. Set it to true, if you want to cache view during development; view caching is enabled in production by default.

js
app.render('email', (err, html) => {
  // ...
});

app.render('email', { name: 'Tobi' }, (err, html) => {
  // ...
});

app.route() ​

Parameters

  • path · String

    The path of the route to create.

Returns: Route

Returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).

js
const app = express();

app
  .route('/events')
  .all((req, res, next) => {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
  })
  .get((req, res, next) => {
    res.json({});
  })
  .post((req, res, next) => {
    // maybe add a new event...
  });
ts
import express, { type Express, type Request, type Response, type NextFunction } from 'express';

const app: Express = express();

app
  .route('/events')
  .all((req: Request, res: Response, next: NextFunction) => {
    // runs for all HTTP verbs first
    // think of it as route specific middleware!
  })
  .get((req: Request, res: Response, next: NextFunction) => {
    res.json({});
  })
  .post((req: Request, res: Response, next: NextFunction) => {
    // maybe add a new event...
  });

app.set() ​

Parameters

  • name · String

    The name of the setting to assign. Certain names configure the server's behavior; see the app settings table.

  • value · any

    The value to assign to the setting.

Returns: Application

Assigns setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.

Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').

Retrieve the value of a setting with app.get().

js
app.set('title', 'My Site');
app.get('title'); // "My Site"

Application Settings ​

The following table lists application settings.

INFO

Sub-apps will:

  • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  • Inherit the value of settings with no default value; these are explicitly noted in the table below.
  • Inherit case sensitive routing and strict routing unless those settings are explicitly set on the sub-app. These values configure the sub-app's router when it is created; mounting does not reconfigure an existing router. If a parent uses path-specific middleware to protect a sub-app, apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it.

Exceptions: Sub-apps will inherit the value of trust proxy even though it has a default value (for backward-compatibility); Sub-apps will not inherit the value of view cache in production (when NODE_ENV is "production").

Settings

  • case sensitive routing · Boolean · default: N/A (undefined)

    Enable case sensitivity. When enabled, "/Foo" and "/foo" are different routes. When disabled, "/Foo" and "/foo" are treated the same.

    This setting is read when the app first creates its router. Adding a route or middleware, calling app.param(), accessing app.router, or handling a request can create the router. Set it before any of these operations. Changing it afterwards has no effect on routing, including routes added later.

    INFO

    Sub-apps inherit this setting unless they explicitly set their own value. If the sub-app's router already exists when the setting is inherited, subApp.get('case sensitive routing') reports the inherited value, but the router keeps its original configuration. To avoid relying on mount order, set case sensitive routing on the sub-app before its router is created.

  • env · String · default: process.env.NODE_ENV (NODE_ENV environment variable) or "development" if NODE_ENV is not set.

    Environment mode. Be sure to set to "production" in a production environment; see Production best practices: performance and reliability.

  • etag · Boolean | String | Function · default: weak

    Set the ETag response header. For possible values, see the etag options table below. More about the HTTP ETag header.

  • jsonp callback name · String · default: "callback"

    Specifies the default JSONP callback name.

  • json escape · Boolean · default: N/A (undefined)

    Enable escaping JSON responses from the res.json, res.jsonp, and res.send APIs. This will escape the characters <, >, and & as Unicode escape sequences in JSON. The purpose of this is to assist with mitigating certain types of persistent XSS attacks when clients sniff responses for HTML.

    INFO

    Sub-apps will inherit the value of this setting.

  • json replacer · Function | Array · default: N/A (undefined)

    The 'replacer' argument used by JSON.stringify.

    INFO

    Sub-apps will inherit the value of this setting.

  • json spaces · Number | String · default: N/A (undefined)

    The 'space' argument used by JSON.stringify. This is typically set to the number of spaces to use to indent prettified JSON.

    INFO

    Sub-apps will inherit the value of this setting.

  • query parser · Boolean | String | Function · default: "simple"

    Disable query parsing by setting the value to false, or set the query parser to use either "simple" or "extended" or a custom query string parsing function. The simple query parser is based on Node's native query parser, querystring. The extended query parser is based on qs. A custom query string parsing function will receive the complete query string, and must return an object of query keys and their values.

  • strict routing · Boolean · default: N/A (undefined)

    Enable strict routing. When enabled, the router treats "/foo" and "/foo/" as different. Otherwise, the router treats "/foo" and "/foo/" as the same.

    This setting is read when the app first creates its router. Adding a route or middleware, calling app.param(), accessing app.router, or handling a request can create the router. Set it before any of these operations. Changing it afterwards has no effect on routing, including routes added later.

    INFO

    Sub-apps inherit this setting unless they explicitly set their own value. If the sub-app's router already exists when the setting is inherited, subApp.get('strict routing') reports the inherited value, but the router keeps its original configuration. To avoid relying on mount order, set strict routing on the sub-app before its router is created.

  • subdomain offset · Number · default: 2

    The number of dot-separated parts of the host to remove to access subdomain.

  • trust proxy · Boolean | String | Number | Function | Array · default: false (disabled)

    Indicates the app is behind a front-facing proxy, and to use the X-Forwarded-* headers to determine the connection and the IP address of the client.

    INFO

    X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.

    When enabled, Express attempts to determine the IP address of the client connected through the front-facing proxy, or series of proxies. The req.ips property, then contains an array of IP addresses the client is connected through. To enable it, use the values described in the trust proxy options table below. The trust proxy setting is implemented using the proxy-addr package. For more information, see its documentation.

    INFO

    Sub-apps will inherit the value of this setting, even though it has a default value.

  • views · String | Array · default: process.cwd() + '/views'

    A directory or an array of directories for the application's views. If an array, the views are looked up in the order they occur in the array.

  • view cache · Boolean · default: true in production, otherwise undefined.

    Enables view template compilation caching.

    INFO

    Sub-apps will not inherit the value of this setting in production (when NODE_ENV is "production").

  • view engine · String · default: N/A (undefined)

    The default engine extension to use when omitted.

    INFO

    Sub-apps will inherit the value of this setting.

  • view engines · String | Array · default: N/A (undefined) · fork addition

    More engine extensions to try, in order, for a view name without a known extension. Off unless it lists at least one extension. See Several template engines.

    INFO

    Sub-apps will inherit the value of this setting.

  • x-powered-by · Boolean · default: true

    Enables the "X-Powered-By: Express" HTTP header.

Options for trust proxy setting ​

Read Express behind proxies for more information.

Boolean: If true, the client's IP address is understood as the left-most entry in the X-Forwarded-* header. If false, the app is understood as directly facing the Internet and the client's IP address is derived from req.connection.remoteAddress. This is the default setting.

String / String containing comma-separated values / Array of strings: An IP address, subnet, or an array of IP addresses, and subnets to trust. Pre-configured subnet names are:

  • loopback - 127.0.0.1/8, ::1/128
  • linklocal - 169.254.0.0/16, fe80::/10
  • uniquelocal - 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, fc00::/7

Set IP addresses in any of the following ways:

Specify a single subnet:

js
app.set('trust proxy', 'loopback');

Specify a subnet and an address:

js
app.set('trust proxy', 'loopback, 123.123.123.123');

Specify multiple subnets as CSV:

js
app.set('trust proxy', 'loopback, linklocal, uniquelocal');

Specify multiple subnets as an array:

js
app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);

When specified, the IP addresses or the subnets are excluded from the address determination process, and the untrusted IP address nearest to the application server is determined as the client's IP address.

Number: Trust the nth hop from the front-facing proxy server as the client.

Function: Custom trust implementation. Use this only if you know what you are doing.

js
app.set('trust proxy', (ip) => {
  if (ip === '127.0.0.1' || ip === '123.123.123.123')
    return true; // trusted IPs
  else return false;
});

Options for etag setting ​

INFO

These settings apply only to dynamic files, not static files. The express.static middleware ignores these settings.

The ETag functionality is implemented using the etag package. For more information, see its documentation.

Values

  • Boolean

    true enables weak ETag. This is the default setting. false disables ETag altogether.

  • String

  • Function

    Custom ETag function implementation. Use this only if you know what you are doing.

js
app.set('etag', (body, encoding) => {
  return generateHash(body, encoding); // consider the function is defined
});

app.use() ​

Parameters

  • path · String | RegExp | Array · optional

    The path for which the middleware function is invoked; can be any of: a string representing a path, a path pattern, a regular expression pattern to match paths, or an array of combinations of any of the above. For examples, see Path examples.

  • callback · Function | Function[]

    Callback functions; can be: a middleware function, a series of middleware functions (separated by commas), an array of middleware functions, or a combination of all of the above. You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route. Since router and app implement the middleware interface, you can use them as you would any other middleware function. For examples, see Middleware callback function examples.

Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.

Description ​

With a string path, app.use() matches that path and its subpaths. For example, app.use('/apple', ...) matches /apple, /apple/images, and /apple/images/news, but not /apples.

Since path defaults to "/", middleware mounted without a path will be executed for every request to the app. For example, this middleware function will be executed for every request to the app:

js
app.use((req, res, next) => {
  console.log('Time: %d', Date.now());
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use((req: Request, res: Response, next: NextFunction) => {
  console.log('Time: %d', Date.now());
  next();
});

INFO

Sub-apps will:

  • Not inherit the value of settings that have a default value. You must set the value in the sub-app.
  • Inherit the value of settings with no default value.

For details, see Application settings.

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

js
// this middleware will not allow the request to go beyond it
app.use((req, res, next) => {
  res.send('Hello World');
});

// requests will never reach this route
app.get('/', (req, res) => {
  res.send('Welcome');
});
ts
import { type Request, type Response, type NextFunction } from 'express';

// this middleware will not allow the request to go beyond it
app.use((req: Request, res: Response, next: NextFunction) => {
  res.send('Hello World');
});

// requests will never reach this route
app.get('/', (req: Request, res: Response) => {
  res.send('Welcome');
});

Error-handling middleware

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don't need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: Error handling.

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):

js
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Path examples ​

The following table provides some simple examples of valid path values for mounting middleware.

Path: Matches the exact path /abcd and any sub-paths starting with /abcd/ (for example, /abcd/foo):

js
app.use('/abcd', (req, res, next) => {
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use('/abcd', (req: Request, res: Response, next: NextFunction) => {
  next();
});

Path Pattern: This will match paths starting with /abcd and /abd:

js
app.use('/ab{c}d', (req, res, next) => {
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use('/ab{c}d', (req: Request, res: Response, next: NextFunction) => {
  next();
});

Regular Expression: This will match paths starting with /abc and /xyz:

js
app.use(/\/abc|\/xyz/, (req, res, next) => {
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use(/\/abc|\/xyz/, (req: Request, res: Response, next: NextFunction) => {
  next();
});

Array: This will match paths starting with /abcd, /xyza, /lmn, and /pqr:

js
app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req, res, next) => {
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], (req: Request, res: Response, next: NextFunction) => {
  next();
});

Middleware callback function examples ​

The following table provides some simple examples of middleware functions that can be used as the callback argument to app.use(), app.METHOD(), and app.all().

Single Middleware: You can define and mount a middleware function locally.

js
app.use((req, res, next) => {
  next();
});
ts
import { type Request, type Response, type NextFunction } from 'express';

app.use((req: Request, res: Response, next: NextFunction) => {
  next();
});

A router is valid middleware.

js
const router = express.Router();
router.get('/', (req, res, next) => {
  next();
});
app.use(router);
ts
import express, { type Request, type Response, type NextFunction } from 'express';

const router = express.Router();
router.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});
app.use(router);

An Express app is valid middleware.

js
const subApp = express();
subApp.get('/', (req, res, next) => {
  next();
});
app.use(subApp);
ts
import express, { type Express, type Request, type Response, type NextFunction } from 'express';

const subApp: Express = express();
subApp.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});
app.use(subApp);

Series of Middleware: You can specify more than one middleware function at the same mount path.

js
const r1 = express.Router();
r1.get('/', (req, res, next) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req, res, next) => {
  next();
});

app.use(r1, r2);
ts
import express, { type Request, type Response, type NextFunction } from 'express';

const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

app.use(r1, r2);

Array: Use an array to group middleware logically.

js
const r1 = express.Router();
r1.get('/', (req, res, next) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req, res, next) => {
  next();
});

app.use([r1, r2]);
ts
import express, { type Request, type Response, type NextFunction } from 'express';

const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

app.use([r1, r2]);

Combination: You can combine all the above ways of mounting middleware.

js
function mw1(req, res, next) {
  next();
}
function mw2(req, res, next) {
  next();
}

const r1 = express.Router();
r1.get('/', (req, res, next) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req, res, next) => {
  next();
});

const subApp = express();
subApp.get('/', (req, res, next) => {
  next();
});

app.use(mw1, [mw2, r1, r2], subApp);
ts
import express, { type Express, type Request, type Response, type NextFunction } from 'express';

function mw1(req: Request, res: Response, next: NextFunction) {
  next();
}
function mw2(req: Request, res: Response, next: NextFunction) {
  next();
}

const r1 = express.Router();
r1.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

const r2 = express.Router();
r2.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

const subApp: Express = express();
subApp.get('/', (req: Request, res: Response, next: NextFunction) => {
  next();
});

app.use(mw1, [mw2, r1, r2], subApp);

Following are some examples of using the express.static middleware in an Express app.

Serve static content for the app from the "public" directory in the application directory:

js
// GET /style.css etc
app.use(express.static(path.join(__dirname, 'public')));

Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static":

js
// GET /static/style.css etc.
app.use('/static', express.static(path.join(__dirname, 'public')));

Disable logging for static content requests by loading the logger middleware after the static middleware:

js
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger());

Serve static files from multiple directories, but give precedence to "./public" over the others:

js
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'files')));
app.use(express.static(path.join(__dirname, 'uploads')));

An unofficial fork of Express, not the official project. Code: MIT. Docs adapted from expressjs.com by the Express contributors, CC BY 4.0, with changes (details).