nestjsfastifynestjs-fastify

Using subdomains in NestJS with Fastify Adapter?


The docs state that Fastify doesn't support nested routers, however they do support a Route Config which in theory should allow me to use constraints to limit a route to a sub domain, such as the following:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { RouteConfig } from '@nestjs/platform-fastify';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @RouteConfig({
    constraints: { host: 'admin.example.com' },
  })
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

This doesn't work in practice however, and seems to resolve to the same route regardless of top-level or subdomain resolution.


Solution

  • My answer might be a bit late, but my PR to add this feature was merged only today.

    In previous versions of @nestjs/platform-fastify (< v10.3) you wouldn't be able to use @RouteConfig as that only implements Fastitfy's route config feature.

    If possible, update your @nestjs/platform-fastify to a recent version (>= v10.3.0) and use @RouteConstraints decorator:

    import { Controller, Get } from '@nestjs/common';
    import { AppService } from './app.service';
    import { RouteConstraints } from '@nestjs/platform-fastify';
    
    @Controller()
    export class AppController {
      constructor(private readonly appService: AppService) {}
    
      @RouteConstraints({
        host: 'admin.example.com',
      })
      @Get()
      getHello(): string {
        return this.appService.getHello();
      }
    }
    

    References:

    Thank you for pointing to this issue and giving me an opportunity to do some OSS contributions :)