Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a middleware before Nest Js ServeStaticModule

I want to run a middleware before Nest JS serves my React application using ServeStatic Module. I cannot get a nest middleware or even a Global middleware to run on any static routes other than '/'

main.ts

app.use([AuthRedirectMiddleware, VerifyMiddleware]);

// Or even a simple logger

app.use(function (req, res, next) {
   console.log("LOG: ", req.originalUrl);
   next();
});

// All 3 middlewares only run for / and /api*
// Does not run for /posts , /orders/123 (both are front end routes)

This is only working for API routes and '/'

My static serve module is setup like this:

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot(),
    ServeStaticModule.forRoot({
      rootPath: clientPath,
      exclude: ["/api*"],
    }),
    SharedModule,
    ...
  ],
  controllers: [],
  providers: [],
})

I also have a globalPrefix for api routes in main.js. So all urls except for /api* go to the react application

 app.setGlobalPrefix("api");
like image 804
Geon George Avatar asked Oct 18 '25 15:10

Geon George


1 Answers

This solution works as long are you are using NestJS to serve your static files (Angular/React index.html, images, JS files, etc). If you are developing locally and serving Angular/React through their native dev-serve modes (like on port 4200), you are by-passing NestJS and therefore not running any middleware.

// main.ts
app.use(globalMiddleware);
// global.middleware.ts
export function globalMiddleware(req: Request, res: Response, next: NextFunction) {
  res.setHeader('Test-Header', 'Test-Value');
  next();
}
// app.module.ts
@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: clientPath,
      exclude: ['/api/(.*)'],
    }),
  ],
})

If you set up the above code, going to any route (/, /api/, /posts, /orders/123) will set the response header Test-Header. Just make sure you are making a request to NestJS (usually on port 3000 or 3333).

First, Nest runs globally bound middleware (such as middleware bound with app.use) and then it runs module bound middleware, which are determined on paths

Source: https://docs.nestjs.com/faq/request-lifecycle#request-lifecycle

like image 124
Elte156 Avatar answered Oct 20 '25 05:10

Elte156