API Versioning in NestJS: How We Choose URI vs Header Versioning, Send Deprecation and Sunset Headers, and Keep Old Mobile Clients Working
Table of Contents
About the Author

Ahmed Mahmoud
Author & Developer
Software engineer passionate about web development and user experience design.
Founder of Devya · eng-ahmed.com ↗Most API changes do not need a new version; only breaking changes do, and in NestJS we handle those per route with URI versioning, @Version() and one shared service layer. When we retire a version, we announce it in every response with the Deprecation (RFC 9745) and Sunset (RFC 8594) headers, and we pick the shutdown date from request logs, because old mobile app builds keep calling an API long after the web frontend has moved on.
API versioning is the practice of serving more than one contract for the same resource, so existing clients keep working while new clients get a changed shape. A web frontend deploys together with its backend and can switch contracts the same day. A mobile app installed from the App Store or Google Play cannot: some users run builds that are months old. At Devya, most of the APIs we build serve both kinds of client, so these are our field notes on versioning NestJS APIs and retiring old versions without breaking anyone.
Key takeaways
Version only breaking changes: a new endpoint or a new optional response field ships without a new version; removing, renaming or retyping a field needs one.
URI versioning is our default: /api/v2/orders shows up in access logs, works with plain curl, and gets its own CDN cache key without a Vary header.
Version per route, not per app: a NestJS controller can serve version: ['1', '2'] and override only the handler that changed with @Version('2').
Keep one service layer: v1 and v2 handlers call the same service and differ only in their response mappers.
Announce retirement in the response: send Deprecation, Sunset and Link: rel="deprecation" headers, expose them through CORS, and return 410 Gone after the sunset date.
When does an API change actually need a new version?
An API change needs a new version only when a client written against the old contract would break. Every other change is additive, and existing clients ignore it. We keep the list below in the pull request template of our API repositories, because the expensive mistakes we have seen were breaking changes nobody recognized as breaking.
Changes that need a new API version: removing or renaming a response field; changing a field's type or unit, for example a decimal total becoming integer minor units plus a currency code; making an optional request field required, or tightening validation, for example enabling forbidNonWhitelisted on ValidationPipe while old clients still send extra fields; and changing status codes, the error body shape, or the default sort order and page size of a list endpoint.
Changes that usually do not: a new endpoint, a new optional request field, or a new response field. One grey area deserves a warning. Adding a value to an enum is additive on the server, but it breaks clients that switch exhaustively over the enum without a default branch, which is common in Swift and Kotlin. We treat new enum values as breaking for mobile clients unless the contract documented an unknown fallback from day one.
Should a NestJS API be versioned in the URL or in a header?
For APIs consumed by browsers, mobile apps and third parties, we version in the URL. NestJS supports four strategies through app.enableVersioning(), and the trade-offs between them are operational, not aesthetic:
URI (VersioningType.URI): GET /api/v2/orders. Separate CDN cache key by default, visible in access logs, works with plain curl.
HEADER (VersioningType.HEADER): X-API-Version: 2. Needs Vary: X-API-Version on every shared cache, visible in logs only if the header is logged, needs -H in curl.
MEDIA_TYPE (VersioningType.MEDIA_TYPE): Accept: application/json;v=2. Needs Vary: Accept, rarely visible in logs, needs -H in curl.
CUSTOM (VersioningType.CUSTOM): any rule inside an extractor function; caching and logging behavior depend on the rule.
Header and media-type versioning give cleaner URLs, but every shared cache between the client and the API must honor the Vary header, or a v1 response gets served to a v2 client. URI versioning removes that class of bug entirely. The CUSTOM type fits schemes such as date-based versions; its extractor function returns either one version or an array ordered from highest to lowest, so NestJS can pick the highest version that has a matching handler.
How do you set up API versioning in NestJS?
NestJS versioning is enabled once in main.ts and then declared on controllers and handlers. The API has been stable since NestJS 8; we last checked these types against @nestjs/common 12.6.
Our main.ts calls app.setGlobalPrefix('api'), then app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1' }), then app.enableCors() with exposedHeaders set to Deprecation, Sunset and Link.
The orders controller is declared with @Controller({ path: 'orders', version: ['1', '2'] }), so its list handler is served at both /api/v1/orders and /api/v2/orders. The single-order handler is split into findOneV1 with @Version('1') and findOneV2 with @Version('2'), both on @Get(':id') and both calling the same OrdersService. The health controller is declared with version: VERSION_NEUTRAL, so it is served at /api/health with no version segment.
Three details caught us the first time. First, defaultVersion is not the version used when a request carries none; it is the version assigned to controllers and handlers that declare no version. With URI versioning, an undecorated controller therefore answers at /api/v1/…, and a request to /api/orders returns 404. Second, VERSION_NEUTRAL matches any requested version or none, and with URI versioning a version-neutral route has no version segment, which is what load-balancer health checks and registered webhook URLs need. Third, the version segment comes after the global prefix, so paths look like /api/v1/orders, not /v1/api/orders.
How do you share logic between v1 and v2 without duplicating it?
API versioning belongs at the edge: v1 and v2 handlers call the same service, and only the response mapper differs. Business rules, database queries and authorization exist once. In our example, v2 changed money from a decimal number to integer minor units plus a currency code, which is a type-and-unit change and therefore breaking.
The toOrderV2 mapper returns total as an object with amountMinor and currency. The toOrderV1 mapper keeps the legacy shape: total is order.totalMinor / 100 as a decimal (valid for 2-decimal currencies only), and the status passes through toLegacyStatus().
The v1 mapper is also where we absorb other contract drift, such as collapsing a newer enum value into an older one. We keep one contract test per version that snapshots the response shape, so a change to the shared Order type that leaks into v1 fails CI instead of failing an old app in production. When the domain drifts so far that a mapper can no longer express v1, that is our signal to schedule the v1 sunset, not to fork the service.
How do you tell clients that an API version is going away?
We announce deprecation inside every response of the old version, using standard HTTP headers that clients, API gateways and log pipelines can detect. The Deprecation header, standardized in RFC 9745 in 2025, carries the date the resource was deprecated as a structured-field date in Unix seconds, for example Deprecation: @1796083200 for 1 December 2026. The Sunset header, defined in RFC 8594, carries the HTTP date after which the resource is expected to stop responding. A Link header with rel="deprecation" points to the migration guide.
A custom decorator plus a global interceptor keeps this declarative. The @Deprecated() decorator stores deprecatedAt, sunsetAt and guideUrl with SetMetadata. The DeprecationInterceptor reads them with Reflector.getAllAndOverride() from the handler or the controller, then sets Deprecation to @ followed by the Unix seconds, Sunset to new Date(sunsetAt).toUTCString(), and Link to the guide URL with rel="deprecation".
We register the interceptor with the APP_INTERCEPTOR provider and put @Deprecated() on findOneV1. The interceptor sets the headers before the handler runs, so errors thrown by the old handler carry them too. Two gotchas apply. Browsers only let frontend JavaScript read these headers when CORS lists them in Access-Control-Expose-Headers, which is what exposedHeaders in enableCors() configures. And setHeader('Link', …) replaces any existing Link header, so append instead if another layer already sets one. On the Fastify adapter, use reply.header() instead of setHeader().
How do you know when it is safe to switch an old API version off?
The sunset date should come from traffic data, not from the calendar. We add two fields to every structured request log line: the API version taken from the path, and the client app version from an X-App-Version header that our mobile apps send. With those fields, "who still calls v1, and on which builds" is one log query. Web traffic on v1 usually drops to zero within one deploy, because the web frontend ships with the backend. Mobile traffic decays slowly, and a tail of devices that rarely update can stay on an old build for a long time.
An old app build cannot read a Deprecation header and rewrite itself, so for mobile we pair the headers with a minimum-supported-version check. A VERSION_NEUTRAL config endpoint returns minSupportedAppVersion, and the app shows a blocking update screen when it is below that value. The check only helps if it shipped in the oldest build still in use, so we add it to the first release of every app. A few weeks before the sunset date, we raise the minimum to the first build that speaks v2. After the sunset date, the v1 handlers stay registered but return 410 Gone with a JSON body that links to the migration guide, which is a clearer failure than a 404 for a route that seems never to have existed. We delete the v1 code one release later.
FAQ
Q: Does NestJS support API versioning out of the box?
A: Yes. Since NestJS 8, app.enableVersioning() from @nestjs/common supports URI, header, media-type and custom versioning, and routes are versioned with @Controller({ version }) or the @Version() decorator.
Q: What does VERSION_NEUTRAL do in NestJS?
A: VERSION_NEUTRAL marks a controller or route that matches any requested version or no version at all. With URI versioning, a version-neutral route is served without a version segment, which suits health checks and webhook receivers.
Q: What is the difference between the Deprecation and Sunset HTTP headers?
A: The Deprecation header (RFC 9745) states that a resource is deprecated, and since when, while it still works. The Sunset header (RFC 8594) states when the resource is expected to stop responding. Send both, plus a Link header with rel="deprecation" that points to a migration guide.
Q: Should API URLs contain full semantic versions such as v2.1.0?
A: No. Put only the major version in the URL, because only breaking changes need a new contract. Additive changes ship inside the current major version without a version bump.
Q: What status code should a retired API version return?
A: A retired API version should return 410 Gone with a JSON body that links to the migration guide. A 410 tells clients and monitoring that the endpoint existed and was removed on purpose, while a 404 looks like a client bug.
Further Reading
Backend Engineering
NestJS ValidationPipe in Production: How We Use whitelist, Nested DTOs and Explicit Transforms to Stop Bad Input
NestJS's ValidationPipe validates only what DTO decorators describe, so its defaults let extra fields, unvalidated nested objects and mis-converted query strings through. These are the settings our team ships in every NestJS API: whitelist and forbidNonWhitelisted against mass assignment, @Type() for nested DTOs, explicit query transforms instead of enableImplicitConversion, and APP_PIPE so e2e tests validate too.
Backend Engineering
Transactional Email from Next.js and Node.js: How We Set Up SPF, DKIM, DMARC, React Email and Resend
Transactional email lands in spam when the From domain fails DMARC, not because of the template. This is the setup our team ships by default from Next.js and NestJS: aligned SPF, DKIM and DMARC records, React Email templates sent through Resend with idempotency keys, signed bounce and complaint webhooks, and one-click unsubscribe where the Gmail and Yahoo sender rules require it.