Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 43 ยท Routing

Application Settings, Sub-Apps and Mount Events

Learn Express application settings (app.set, app.get, enable, disable, etag, case sensitive routing, json spaces, trust proxy) and how mounted sub-apps inherit them.

Every Express application carries a small table of settings: switches and values that change how Express itself behaves. Whether /Books and /books are the same route, how many spaces res.json uses when it prints, whether a weak ETag is added to responses, whether the X-Powered-By header is sent, which proxies to trust: all of these are settings. You change them with app.set() and read them with app.get().

The same object model lets you do something more ambitious: an Express application can be mounted inside another one. A sub-app is a complete express() instance with its own settings, its own routes and its own error handling, attached to a path of a parent app. This lesson covers both ideas, using runnable stand-ins that copy the behavior of the real thing closely enough to see it work.

Settings in one slide

set and get app.set(name, value) and app.get(name).
enable and disable Shortcuts for true and false.
enabled and disabled Ask whether a flag is on.
1 / 2

Reading and writing settings

The API is tiny:

JavaScript
app.set('title', 'My Shop');     // write any name and value
app.get('title');                // 'My Shop' (read it back)

app.enable('trust proxy');       // same as app.set('trust proxy', true)
app.disable('x-powered-by');     // same as app.set('x-powered-by', false)

app.enabled('x-powered-by');     // false: true when the setting is truthy
app.disabled('x-powered-by');    // true: true when the setting is falsy

You may store your own values this way too (app.set('title', ...)), and handlers read them through req.app.get('title'). For application-wide constants that is fine, but plain modules and a config object (see Project Setup) are usually clearer. Settings are mostly for Express's own switches.

app.get() has two jobs. With one argument it reads a setting. With a path and handlers (app.get('/books', handler)) it registers a route. Express tells them apart by the number of arguments.

The settings you will meet

Setting Default What it does
env process.env.NODE_ENV or 'development' The environment name your code can branch on.
etag 'weak' Adds an ETag header to res.send/res.json responses. Use false to turn it off, 'strong' for strong ETags.
x-powered-by true Sends X-Powered-By: Express. Turn it off: it tells attackers which framework you use. Helmet does the same.
case sensitive routing off When off, /Books and /books match the same route.
strict routing off When off, /books and /books/ match the same route.
json spaces none Indentation used by res.json. Handy in development: app.set('json spaces', 2).
json replacer, json escape none, off Replacer passed to JSON.stringify; escaping of <, >, & in JSON bodies.
query parser 'simple' How req.query is parsed. Express 5 defaults to the simple Node parser; 'extended' supports nested a[b]=1.
trust proxy false Which proxies to believe when reading X-Forwarded-* headers (The Request Object).
subdomain offset 2 How many dot-separated parts form the domain for req.subdomains.
views, view engine, view cache ./views, none, on in production Template settings (Template Engines).
jsonp callback name 'callback' The query parameter name used by res.jsonp.

Two of them deserve emphasis because of their security impact. x-powered-by should be disabled in production. trust proxy must never be set to a blanket true on a server that is also directly reachable from the internet: anyone could then send a fake X-Forwarded-For header and forge their IP address. Set it to the number of proxy hops you control (1 behind one load balancer) or to specific addresses.

Watching settings change behavior

The Express source is not installed on this site, so the example below uses a stand-in: a small express() written for this lesson that implements the settings API (set, get, enable, disable, enabled, disabled) and a handful of the real behaviors: case-sensitive and strict routing, json spaces, x-powered-by and etag. The comparisons it prints are the same ones you would see with real Express.

Node.js Settings in action: routing, json spaces, etag, x-powered-by

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from top to bottom. With defaults, /BOOKS and /books/ both reach the route and the response has an ETag. After enabling case sensitive routing and strict routing, the same two URLs return 404. Setting json spaces pretty-prints the body (the \n markers show the line breaks), disabling etag removes the header, and re-enabling x-powered-by brings its header back. The values are read each time a request arrives, so you can change a setting at runtime.

In real Express, app.set('etag', 'strong'), app.set('etag', false) or even a custom function are accepted. For a JSON API behind a CDN, the default weak ETag is usually what you want; for huge dynamic responses that are never cached, turning ETags off saves hashing work.

Sub-apps: an app inside an app

A router (see Modular Routing) groups routes. A sub-app goes further: it is a full express() application. Mounting one uses use() just like middleware:

JavaScript
const admin = express();          // a separate application
admin.get('/', (req, res) => res.send('Admin home'));
admin.get('/users', (req, res) => res.json(['ada', 'grace']));

const app = express();
app.use('/admin', admin);         // /admin and /admin/users are now served by `admin`

When Express sees an express() application passed to use, it does three things:

  1. It stores the mount path in admin.mountpath ('/admin'; it can also be an array or a pattern).
  2. It sets admin.parent to the parent app, which is what powers admin.path(): the full path of the sub-app from the root, such as /api/admin when admin is mounted on an app that is itself mounted on /api.
  3. It emits a mount event on the sub-app, passing the parent. The sub-app can listen for it (admin.on('mount', (parent) => ...)) to react to where it was installed, for example to log, read parent settings or register itself.

Inside the sub-app, the mount prefix is stripped from the URL. req.url and req.path are /users, while req.baseUrl is /admin and req.originalUrl keeps the full /admin/users. This is exactly how express.Router behaves, so code written for a router moves into a sub-app without changes.

What a sub-app inherits

Each app has its own settings table, and mounting links the sub-app's table to its parent's. The rule from the Express documentation:

  • A sub-app does not inherit settings that have a default value. If the parent calls app.disable('etag'), the sub-app keeps its own default etag: 'weak' unless you set it again inside the sub-app.
  • A sub-app does inherit settings that have no default value and are not set in the sub-app: your custom settings, json spaces, and so on.
  • Anything the sub-app sets for itself wins, and the parent never sees it.
Node.js Mounting, mountpath, path() and inheritance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The mount event fired at the moment api.use('/admin', admin) ran. admin.path() was only /admin while api had no parent; once api was mounted on app it printed the full /api/admin. Inside the handler, req.url was /users?page=2 (relative to the mount), req.baseUrl was /api/admin, and req.originalUrl had the complete URL. The parent's etag is false but the sub-app still has 'weak' (it has a default), and the response carries an ETag; the custom app title was inherited until the sub-app set its own.

When to use a sub-app

Sub-apps are not needed for ordinary route grouping: an express.Router is lighter and is what most projects use. Reach for a sub-app when a section needs a different configuration:

  • An /admin area with its own view engine and views folder, error pages and trust proxy setting, while the public site renders differently.
  • A versioned API (/api/v1, /api/v2) where each version is developed and tested as its own application and mounted by the main app.js.
  • A reusable plug-in application shipped as an npm package that exports an express() app. The host app mounts it anywhere with app.use('/blog', blogApp).
  • Separate error handlers per area: an error inside a mounted app goes to that app's error middleware first, then to the parent's.

A sub-app's listen is rarely called: the parent owns the server. In tests you may call the sub-app directly, because an Express app is just a function (req, res).

Common mistakes

  • Expecting parent settings to override defaults in a sub-app. Set etag, x-powered-by, env and similar defaults in each app that needs them.
  • Reading req.url with the full path inside a sub-app. Use req.originalUrl when you need the whole URL, for example in logs and redirects.
  • Mounting before configuring. Settings without a default are inherited through the parent when the sub-app reads them, but routing flags such as case sensitive routing apply when a router is first created, so set them before you register routes.
  • Using app.set('trust proxy', true) as a quick fix. It makes req.ip believable only when every request really passes through your proxy.
  • Forgetting the one-argument app.get. app.get('env') returns a setting; it never registers a route.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does app.get('title') do, compared with app.get('/title', handler)?

    Express overloads app.get: one argument reads a setting, a path plus handlers adds a route.
  2. 2. Which call is equivalent to app.set('x-powered-by', false)?

    disable sets the setting to false. disabled only asks whether it is already falsy.
  3. 3. The parent app calls app.disable('etag'). What does a mounted sub-app do?

    Only settings with no default value and no value of their own are inherited by a sub-app.
  4. 4. Inside a sub-app mounted at /admin, a request arrives for /admin/users. What are req.url and req.baseUrl?

    The mount path is moved from req.url to req.baseUrl; req.originalUrl still has the whole path.
  5. 5. When is the mount event emitted?

    The sub-app emits mount with the parent as the argument when parent.use(path, subApp) runs.

Summary

  • Settings are Express's switches: read with app.get(name), write with app.set(name, value), shortcut with enable, disable, enabled, disabled.
  • Useful settings include env, etag, x-powered-by (turn it off), case sensitive routing, strict routing, json spaces, query parser and trust proxy (never a blanket true on an exposed server).
  • Mount an express() app with parent.use('/path', subApp); it gets mountpath, path() (the full path through every parent), a mount event and its own settings and error handlers.
  • Sub-apps inherit only settings that have no default value; defaults such as etag must be set per app.
  • Inside a sub-app the mount prefix moves from req.url to req.baseUrl; req.originalUrl keeps the whole URL.
  • Prefer a plain router for grouping and a sub-app when a section needs its own configuration.

Next: shape every response precisely in The Response Object, or start a real project with Project Setup.