skip to content

In NestJS, how do you route a tenant sub-domain such as acme.example.com to a controller and read the tenant name with @HostParam?

level: middleimportance: nice to knowfreq 12%

answer

  1. host option on @Controller
  2. a token inside the host pattern
  3. unmatched host skips the route
  4. Fastify adapter not supported

basics

~10 s

Pass a host pattern to the controller, @Controller({ host: ':tenant.example.com' }), and read the captured segment with @HostParam('tenant'). Requests whose host name does not match skip that controller's routes, usually ending in a 404.

solid answer

~40 s

`@Controller()` accepts a `host` option: a string pattern with tokens such as `':tenant.example.com'`, a `RegExp`, or an array of either. On each request Nest matches the pattern against the request's host name; on a match it stores the captured values and runs the handler, where `@HostParam('tenant')` returns `'acme'` for `acme.example.com` and `@HostParam()` returns all host parameters. On a miss the route passes the request on, so another route may serve it or the client gets a 404. With a `RegExp`, named capture groups become the host parameters. The documentation says to use the default Express adapter for this, because Fastify does not support nested routers. The host name comes from Express's `req.hostname`, so behind a load balancer it depends on Express's proxy settings.

go deeper

for a junior

Recall that @Controller can take a host option and that @HostParam reads a token captured from the host name.

for a middle

Explain how the host check wraps each route, why a miss falls through to other routes or a 404, and how RegExp named groups feed @HostParam.

for a senior

Spot the production traps: an earlier unrestricted route stealing traffic, a proxy setting that changes req.hostname, and the Fastify limitation.

for a principal

Weigh tenant-per-sub-domain routing against tenant-in-path or tenant-in-token, given DNS, certificates and how much routing lives in one app.

## Host-restricted controllers Most routing looks only at the path. NestJS can also restrict a whole controller to certain **host names**, which is how a multi-tenant service serves `acme.example.com` and `globex.example.com` from one codebase, or keeps an admin surface on `admin.example.com`. The restriction is the `host` option of `@Controller()`: - a plain string, such as `'admin.example.com'`, for an exact host; - a string with **tokens**, such as `':tenant.example.com'`, that capture part of the host; - a `RegExp`, whose **named capture groups** become host parameters; - an array of any of these, when one controller serves several hosts. A token in a host pattern works like a route parameter in a path. Because the pattern is compiled as if it were a path, whose only delimiter is `/`, a token is not stopped by dots: it captures everything in its position up to the fixed text that follows. ## Reading the captured value ```typescript @Controller({ host: ':tenant.example.com', path: 'info' }) export class TenantController { @Get() info(@HostParam('tenant') tenant: string) { return { tenant }; // acme.example.com -> { tenant: 'acme' } } } ``` `@HostParam('tenant')` returns one captured value; `@HostParam()` without a key returns the object holding all of them. ## What happens on a request 1. The Express adapter has registered the route at its path as usual, wrapped in a host check. 2. Nest takes the request's host name, which on Express is `req.hostname`, and tests it against each host pattern of the controller. 3. On a match it records the captured values on the request and runs the handler, so `@HostParam()` can read them. 4. On a miss it passes the request to the next registered route. If no other route matches, the client receives Nest's 404 (`Cannot GET /info`). | Request host | Pattern `':tenant.example.com'` | Outcome | |---|---|---| | `acme.example.com` | matches, `tenant = 'acme'` | handler runs | | `example.com` | no text in front of `.example.com` | skipped; 404 if nothing else matches | | `a.b.example.com` | matches, `tenant = 'a.b'` (dots are not a boundary) | handler runs | ## RegExp hosts and several hosts A string pattern is enough for most tenants, but a `RegExp` gives full control over what a tenant name may contain: ```typescript @Controller({ host: /^(?<tenant>[a-z0-9-]+)\.example\.org$/ }) export class TenantController {} ``` - **Named capture groups** become host parameters, so `@HostParam('tenant')` reads `(?<tenant>...)` exactly as it reads a `':tenant'` token. - **Anchoring with `^` and `$`** and a character class keeps `a.b.example.org` or `example.org.attacker.net` from matching. - **An array** such as `['admin.example.com', 'admin.example.net']` lets one controller answer several hosts; the first pattern that matches supplies the parameters. ## Things that go wrong - **An unrestricted route registered first wins.** The Express adapter dispatches in registration order, so a controller without `host` that serves the same path and is registered earlier answers every host, and the host-restricted one never runs. - **The adapter matters.** The documentation warns that Fastify does not support nested routers, so use the default Express adapter when you rely on sub-domain routing. - **The proxy decides what `hostname` is.** Behind a load balancer, Express derives `req.hostname` according to its trust-proxy setting; that setting is covered with Express itself, but a wrong value means patterns match the wrong host. - **A token is not limited to one label.** `a.b.example.com` matches `':tenant.example.com'` with `tenant = 'a.b'`; anchor a `RegExp` such as `[a-z0-9-]+` if only single-label tenants are valid. - **Local development needs real host names.** `localhost` never matches `':tenant.example.com'`, so test with a hosts-file entry or a `Host` header. ## When to use it - Tenant-per-sub-domain products where the tenant name selects data. - Splitting an admin or partner surface onto its own host inside one Nest app. - Avoid it when the tenant could equally travel in a path segment or a token claim and you do not control DNS for every customer.

  • In NestJS, how do you read host parameters when the host option is a RegExp instead of a token string?
    Use named capture groups in the `RegExp`, such as `/^(?<tenant>[a-z0-9-]+)\.example\.com$/`. On a match Nest copies each named group onto the request's host parameters, so `@HostParam('tenant')` reads it exactly as with a `':tenant'` token.
  • Why might a host-restricted NestJS controller never run even though its pattern matches?
    On the Express adapter the first registered matching route wins. If a controller without a `host` option serves the same method and path and is registered earlier, it answers every host, so the restricted controller is never reached. Give the general route a different path or restrict both.

  • @HostParam reads the value of a custom tenant header.
  • A request from a non-matching host gets a 403 from Nest.
  • Host-based routing works the same on the Fastify adapter.
  • A host token stops at the first dot, so a.b.example.com never matches.
  • @Controller's host option filters only the first route in the class.