nestjs

How to rewrite url path in Nestjs?


I want to rewrite url like '/api/example' to '/example'

I've tried code below, but it does not work

import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class RewriteApiEndpointMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    req.originalUrl = req.originalUrl.replace(/^\/api/, '');
    next();
  }
}

Solution

  • I have found the solution

    Step 1:

    consumer
      .apply(RewriteApiEndpointMiddleware)
      .forRoutes('/') // <--- not the .forRoutes('*')
    

    Step 2:

    import { Injectable, NestMiddleware } from '@nestjs/common';
    
    @Injectable()
    export class RewriteApiEndpointMiddleware implements NestMiddleware {
      use(req: any, res: any, next: () => void) {
        req.url = req.url.replace(/^\/api/, ''); // <--- not the .originalUrl
        next();
      }
    }
    

    Now it works as expected