Migration guide

This article provides a set of guidelines for migrating from Nest version 6 to version 7.

Custom route decorators

The Custom decorators API has been unified for all types of applications. Now, whether you’re creating a GraphQL application or a REST API, the factory passed into the createParamDecorator() function will take the ExecutionContext (read more here) object as a second argument.

  1. // Before
  2. import { createParamDecorator } from '@nestjs/common';
  3. export const User = createParamDecorator((data, req) => {
  4. return req.user;
  5. });
  6. // After
  7. import { createParamDecorator, ExecutionContext } from '@nestjs/common';
  8. export const User = createParamDecorator(
  9. (data: unknown, ctx: ExecutionContext) => {
  10. const request = ctx.switchToHttp().getRequest();
  11. return request.user;
  12. },
  13. );
  1. // Before
  2. import { createParamDecorator } from '@nestjs/common';
  3. export const User = createParamDecorator((data, req) => {
  4. return req.user;
  5. });
  6. // After
  7. import { createParamDecorator } from '@nestjs/common';
  8. export const User = createParamDecorator((data, ctx) => {
  9. const request = ctx.switchToHttp().getRequest();
  10. return request.user;
  11. });

Microservices

To avoid code duplication, the MicroserviceOptions interface has been removed from the @nestjs/common package. Therefore, now when you’re creating a microservice (through either createMicroservice() or connectMicroservice() method), you should pass the type generic parameter to get code autocompletion.

  1. // Before
  2. const app = await NestFactory.createMicroservice(AppModule);
  3. // After
  4. const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule);
  1. // Before
  2. const app = await NestFactory.createMicroservice(AppModule);
  3. // After
  4. const app = await NestFactory.createMicroservice(AppModule);

Hint The MicroserviceOptions interface is exported from the @nestjs/microservices package.

GraphQL

In the version 6 major release of NestJS, we introduced the code-first approach as a compatibility layer between the type-graphql package and the @nestjs/graphql module. Eventually, our team decided to reimplement all the features from scratch due to a lack of flexibility. To avoid numerous breaking changes, the public API is backward-compatible and may resemble type-graphql.

In order to migrate your existing application, simply rename all the type-graphql imports to the @nestjs/graphql. If you used more advanced features, you might need to also:

  • use Type (imported from @nestjs/common) instead of ClassType (imported from type-graphql)
  • move methods that require @Args() from object types (classes annotated with @ObjectType() decorator) under resolver classes (and use @ResolveField() decorator instead of @Field())

Terminus

In the version 7 major release of @nestjs/terminus, a new simplified API has been introduced to run health checks. The previously required peer dependency @godaddy/terminus has been removed, which allows us to integrate our health checks automatically into Swagger! Read more about the removal of @godaddy/terminushere.

For most users, the biggest change will be the removal of the TerminusModule.forRootAsync function. With the next major version, this function will be completely removed. To migrate to the new API, you will need to create a new controller, which will handle your health checks.

  1. // Before
  2. @Injectable()
  3. export class TerminusOptionsService implements TerminusOptionsFactory {
  4. constructor(
  5. private dns: DNSHealthIndicator,
  6. ) {}
  7. createTerminusOptions(): TerminusModuleOptions {
  8. const healthEndpoint: TerminusEndpoint = {
  9. url: '/health',
  10. healthIndicators: [
  11. async () => this.dns.pingCheck('google', 'https://google.com'),
  12. ],
  13. };
  14. return {
  15. endpoints: [healthEndpoint],
  16. };
  17. }
  18. }
  19. @Module({
  20. imports: [
  21. TerminusModule.forRootAsync({
  22. useClass: TerminusOptionsService
  23. })
  24. ]
  25. })
  26. export class AppModule { }
  27. // After
  28. @Controller('health')
  29. export class HealthController {
  30. constructor(
  31. private health: HealthCheckService,
  32. private dns: DNSHealthIndicator,
  33. ) { }
  34. @Get()
  35. @HealthCheck()
  36. healthCheck() {
  37. return this.health.check([
  38. async () => this.dns.pingCheck('google', 'https://google.com'),
  39. ]);
  40. }
  41. }
  42. @Module({
  43. imports: [
  44. TerminusModule
  45. ]
  46. })
  47. export class AppModule { }
  1. // Before
  2. @Injectable()
  3. @Dependencies(DNSHealthIndicator)
  4. export class TerminusOptionsService {
  5. constructor(
  6. private dns,
  7. ) {}
  8. createTerminusOptions() {
  9. const healthEndpoint = {
  10. url: '/health',
  11. healthIndicators: [
  12. async () => this.dns.pingCheck('google', 'https://google.com'),
  13. ],
  14. };
  15. return {
  16. endpoints: [healthEndpoint],
  17. };
  18. }
  19. }
  20. @Module({
  21. imports: [
  22. TerminusModule.forRootAsync({
  23. useClass: TerminusOptionsService
  24. })
  25. ]
  26. })
  27. export class AppModule { }
  28. // After
  29. @Controller('/health')
  30. @Dependencies(HealthCheckService, DNSHealthIndicator)
  31. export class HealthController {
  32. constructor(
  33. private health,
  34. private dns,
  35. ) { }
  36. @Get('/')
  37. @HealthCheck()
  38. healthCheck() {
  39. return this.health.check([
  40. async () => this.dns.pingCheck('google', 'https://google.com'),
  41. ])
  42. }
  43. }
  44. @Module({
  45. controllers: [
  46. HealthController
  47. ],
  48. imports: [
  49. TerminusModule
  50. ]
  51. })
  52. export class AppModule { }

Warning If you have set a Global Prefix in your Nest application and you have not used the useGlobalPrefix Terminus option, the URL of your health check will change. Make sure to update the reference to that URL, or use the legacy Terminus API until nestjs/nest#963 is fixed.

If you are forced to use the legacy API, you can also disable deprecation messages for the time being.

  1. TerminusModule.forRootAsync({
  2. useFactory: () => ({
  3. disableDeprecationWarnings: true,
  4. endpoints: [
  5. // ...
  6. ]
  7. })
  8. }

You should enable shutdown hooks in your main.ts file. The Terminus integration will listen on POSIX signals such as SIGTERM (see the Application shutdown chapter for more information). When enabled, the health check route(s) will automatically respond with a Service Unavailable (503) HTTP error response when the server is shutting down.

With the removal of @godaddy/terminus, you will need to update your import statements to use @nestjs/terminus instead. Most notable is the import of the HealthCheckError.

custom.health.ts

  1. // Before
  2. import { HealthCheckError } from '@godaddy/terminus';
  3. // After
  4. import { HealthCheckError } from '@nestjs/terminus';

Once you have fully migrated, make sure you uninstall @godaddy/terminus.

  1. npm uninstall --save @godaddy/terminus

HTTP exceptions body

Previously, the generated response bodies for the HttpException class and other exceptions derived from it (e.g., BadRequestException or NotFoundException) were inconsistent. In the latest major release, these exception responses will follow the same structure.

  1. /*
  2. * Sample outputs for "throw new ForbiddenException('Forbidden resource')"
  3. */
  4. // Before
  5. {
  6. "statusCode": 403,
  7. "message": "Forbidden resource"
  8. }
  9. // After
  10. {
  11. "statusCode": 403,
  12. "message": "Forbidden resource",
  13. "error": "Forbidden"
  14. }

Validation errors schema

In past releases, the ValidationPipe threw an array of the ValidationError objects returned by the class-validator package. Now, ValidationPipe will map errors to a list of plain strings representing error messages.

  1. // Before
  2. {
  3. "statusCode": 400,
  4. "error": "Bad Request",
  5. "message": [
  6. {
  7. "target": {},
  8. "property": "email",
  9. "children": [],
  10. "constraints": {
  11. "isEmail": "email must be an email"
  12. }
  13. }
  14. ]
  15. }
  16. // After
  17. {
  18. "statusCode": 400,
  19. "message": ["email must be an email"],
  20. "error": "Bad Request"
  21. }

If you prefer the previous approach, you can restore it by setting the exceptionFactory function:

  1. new ValidationPipe({
  2. exceptionFactory: (errors) => new BadRequestException(errors),
  3. });

Implicit type conversion (ValidationPipe)

With the auto-transformation option enabled (transform: true), the ValidationPipe will now perform conversion of primitive types. In the following example, the findOne() method takes one argument which represents an extracted id path parameter:

  1. @Get(':id')
  2. findOne(@Param('id') id: number) {
  3. console.log(typeof id === 'number'); // true
  4. return 'This action returns a user';
  5. }

By default, every path parameter and query parameter comes over the network as a string. In the above example, we specified the id type as a number (in the method signature). Therefore, the ValidationPipe will try to automatically convert a string identifier to a number.

Microservice channels (bidirectional communication)

To enable the request-response message type, Nest creates two logical channels - one is responsible for transferring the data while the other waits for incoming responses. For some underlying transports, such as NATS, this dual-channel support is provided out-of-the-box. For others, Nest compensates by manually creating separate channels.

Let’s say that we have a single message handler @MessagePattern('getUsers'). In the past, Nest built two channels from this pattern: getUsers_ack (for requests) and getUsers_res (for responses). With version 7, this naming scheme changes. Now Nest will build getUsers (for requests) and getUsers.reply (for responses) instead. Also, specifically for the MQTT transport strategy, the response channel would be getUsers/reply (to avoid conflicts with topic wildcards).

Deprecations

All deprecations (from Nest version 5 to version 6) have been finally removed (e.g., the deprecated @ReflectMetadata decorator).

Node.js

This release drops support for Node v8. We strongly recommend using the latest LTS version.