1

NestJS URI Versioning for HTTP REST applications can be easily enabled when following the docs here.

The docs do however not explain how to make URI versioning optional.

Example:

/api/v1/users

/api/v2/users

/api/users -> should be mapped to v1 to allow existing webhooks to keep working

Question:

How can we make the URI versioning optional in a NestJS REST application so that old versions (without any api version) keep working ?

2 Answers2

3

You should use the VERSION_NEUTRAL version on defaultVersion option like:

app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: [VERSION_NEUTRAL, '1', '2'],
});

https://docs.nestjs.com/techniques/versioning

Micael Levi
  • 5,054
  • 2
  • 16
  • 27
  • I didn't added this on the docs site because the type defs of `defaultVersion` should tell you can achieve that btw – Micael Levi Jan 17 '22 at 12:22
  • Is there a way we can check if the versioning enabled or not? @MicaelLevi – Raj Mar 28 '22 at 14:37
  • @Raj I guess the only way is by looking at the logs. You'll see `(version: x)` – Micael Levi Mar 28 '22 at 15:24
  • @MicaelLevi I meant I have to check this in code. I have to handle one scenario on the basis of enabled version. – Raj Mar 28 '22 at 17:12
  • This strategy doesn't seem to be allowed. It either accepts `VERSION_NEUTRAL` (a symbol), a version string, or an array of version strings. Not a combination of version strings and a symbol. – Maarten Bicknese Jun 21 '22 at 14:44
  • it is in the latest version. You always can inspect the source: https://github.com/nestjs/nest/blob/61b11ad31506778500ad15c82f94a62774a68000/packages/common/interfaces/version-options.interface.ts#L80 – Micael Levi Jun 21 '22 at 17:55
1

UPDATE:

The following is a hack and results in the global prefix for URI versioning no longer working, please use the accepted answer.

Original Answer:

To make versioning optional, set the versioning prefix to an empty string (default is v) and set the versioning string including the prefix explicitly.

In main.ts:

app.enableVersioning({
    type: VersioningType.URI,
    defaultVersion: ['', 'v1', 'v2'],
    prefix: '',
});

In the v1 controller:

@Controller({ path: 'users', version: ['v1', ''] })