In NestJS, how does app.enableVersioning() with VersioningType URI, HEADER or MEDIA_TYPE route a request to a @Version('1') or @Version('2') handler?
answer
- versions attach to controllers or routes
- URI is the default type
- header name, Accept key
- defaultVersion fills unversioned routes
- VERSION_NEUTRAL matches no version
basics
~20 senableVersioning() makes Nest match the version set by @Controller({ version }) or @Version(). URI, the default, puts /v1 after the global prefix; HEADER reads a named request header; MEDIA_TYPE reads a key such as v= inside Accept. Mismatches return 404.
solid answer
~40 sCall `app.enableVersioning({ type })`; with no argument it uses `VersioningType.URI`. A version comes from `@Controller({ version: '1' })` for every route of a class, or from `@Version('2')` on one method, which overrides the controller's. **URI** registers the route at `/v1/...`, after any global prefix, with `prefix` changing or (`false`) dropping the `v`. **HEADER** compares the value of the header named by `header`; **MEDIA_TYPE** extracts the version after `key` (for example `'v='`) in `Accept: application/json;v=2`. A request whose version matches no route gets a 404. `defaultVersion` gives a version to routes that declare none; it does not give one to requests, so under HEADER a request without the header still 404s unless the route's versions include `VERSION_NEUTRAL`.
code
typescript · 19 linesimport { Controller, Get, Version, VersioningType, VERSION_NEUTRAL } from '@nestjs/common';
// main.ts
app.enableVersioning({
type: VersioningType.HEADER,
header: 'X-API-Version',
defaultVersion: [VERSION_NEUTRAL, '1'],
});
@Controller('orders')
export class OrdersController {
@Version('1')
@Get('report')
reportV1() { return 'v1'; }
@Version('2')
@Get('report')
reportV2() { return 'v2'; }
}go deeper
Recall that enableVersioning() turns versioning on, URI is the default type, and @Version() sets a version on one route.
Explain how each type reads the version, that route versions override controller versions, and why a mismatch is a 404.
Catch the defaultVersion trap under header versioning, where version-less probes and clients suddenly receive 404 until VERSION_NEUTRAL is added.
Judge how many versions a codebase can keep serving from one Nest app and when parallel controllers should give way to a separate deployment.
## What versioning does in Nest **Versioning** lets one NestJS application serve several versions of the same controller or route side by side, so a breaking change can ship as version 2 while version 1 keeps working. Turning it on is one call in the bootstrap file: ```typescript app.enableVersioning({ type: VersioningType.HEADER, header: 'X-API-Version' }); ``` `VersioningType` is exported from `@nestjs/common`. Calling `enableVersioning()` with no argument uses `VersioningType.URI`. Which of these strategies an API should adopt is an HTTP API design question, covered with REST versioning; this answer is about how Nest implements each one. ## Where a route's version comes from - **Controller version**: `@Controller({ path: 'orders', version: '1' })` applies to every route in the class. - **Route version**: `@Version('2')` on a method overrides the controller's version for that method. - **Multiple versions**: either place accepts an array, such as `['1', '2']`. - **`VERSION_NEUTRAL`**: a symbol meaning "match whatever version the request names, including none". - **`defaultVersion`**: an `enableVersioning()` option that gives a version to every controller and route that declares none. ## How each type reads the request | Type | Options | What it compares | Example request for version 2 | |---|---|---|---| | `URI` (default) | `prefix` (default `'v'`, `false` to drop it) | the version segment in the registered path | `GET /api/v2/orders/report` | | `HEADER` | `header` (the header name) | the header's value | `X-API-Version: 2` | | `MEDIA_TYPE` | `key`, including its separator, e.g. `'v='` | the value after the key in `Accept` | `Accept: application/json;v=2` | | `CUSTOM` | `extractor(request)` returning a string or array | the extracted version(s) | anything the function reads | Two mechanisms sit behind that table: 1. **URI versioning changes the path.** Nest registers the route at `/<global prefix>/<prefix><version>/<controller path>/<route path>`. With `app.setGlobalPrefix('api')`, version 1 of `GET orders/report` lives at `/api/v1/orders/report`, never at `/v1/api/...`. 2. **The other types add a version filter.** The route stays at its plain path, and Nest wraps the handler in a check: if the request's version does not match, it passes the request on to the next route, and when none matches the client gets a 404 (`Cannot GET /orders/report`). ## The `defaultVersion` trap `defaultVersion` reads like "the version a request gets when it names none", but it is the version **routes** get when they declare none. The difference shows up under header and media-type versioning: - With `defaultVersion: '1'`, an unversioned health controller becomes a version-1 route. A probe that sends no version header now receives a 404. - A request without the header matches only routes whose versions include `VERSION_NEUTRAL`. - So to keep version-less requests working, set `defaultVersion: [VERSION_NEUTRAL, '1']`, or mark the controller `version: VERSION_NEUTRAL`. Under URI versioning the same option moves unversioned routes to `/v1/...`, so the old unprefixed path disappears. ## Multiple versions and neutral routes A single handler can serve several versions at once, which keeps unchanged endpoints from being copied into every new controller: ```typescript @Controller({ path: 'catalog', version: ['1', '2'] }) export class CatalogController {} ``` - Under URI versioning that controller is registered twice, at `/v1/catalog` and `/v2/catalog`. - A `VERSION_NEUTRAL` controller is registered without any version segment, so under URI versioning it lives at its plain path and answers there whatever version a client has in mind. - Without `defaultVersion`, a route that declares no version is registered without one too: under URI versioning it stays at its plain path, and a `/v1/...` request for it returns 404. - Under URI, header and media-type versioning, a version a client asks for that no route declares is not rounded down to a nearby version; it is simply a 404. When version 1 is finally retired, deleting its `@Version('1')` methods is the whole change: no routing table has to be edited. ## Adapter notes - With a `CUSTOM` extractor on the Express adapter, return a single version: picking the highest match from a multi-version array does not work reliably there, while the Fastify adapter supports it. - Middleware can target one version through the `version` property of a route passed to `MiddlewareConsumer.forRoutes()`; binding middleware is covered with Nest's middleware. ## Checking a setup - Read the "Mapped" lines Nest logs at startup; versioned routes carry their version. - Send one request per version plus one with no version at all, and confirm which handler answers each.
- In NestJS, why does a load balancer's health probe start getting 404 after you add defaultVersion: '1' with header versioning?`defaultVersion` turned the unversioned health controller into a version-1 route, and the probe sends no version header. Under header versioning a request without the header matches only routes that include `VERSION_NEUTRAL`. Mark the health controller `version: VERSION_NEUTRAL` or use `defaultVersion: [VERSION_NEUTRAL, '1']`.
- Where does the version segment go when a NestJS app also calls setGlobalPrefix('api')?After the global prefix and before the controller path: `/api/v1/orders`. Nest builds URI-versioned paths as global prefix, then the `v`-prefixed version, then the controller and route paths, so `/v1/api/orders` returns a 404.
- defaultVersion is the version Nest assumes for requests that send none.
- With URI versioning the version goes before the global prefix.
- A controller version overrides a method's @Version().
- MEDIA_TYPE versioning's key is just the parameter name, without the separator.
- A request for a version no route declares falls back to the newest version.