how to serve assets from Nest.js and add middleware to detect image request how to serve assets from Nest.js and add middleware to detect image request express express

how to serve assets from Nest.js and add middleware to detect image request


The nestjs doc tells you, how to serve static files. In short, here is how you do it:

Specify root directory of your assets in you main.ts

app.useStaticAssets(path.join(__dirname, '/../public'));

Use the @Res annotation to be able to use the sendFile method of express framework

@Get('track/:imgId')test(@Param('imgId') imgId, @Res() res) {  const imgPath = getImgPath(imgId);  return res.sendFile(imgPath, { root: 'public' });}

This solution assumes that your nestjs installation uses express under the hood.


Sources:

Want to add a point here, please make sure you're using:

const app = await NestFactory.create<NestExpressApplication>(AppModule);

Instead of this:

const app = await NestFactory.create(AppModule);

in your main.ts file.


It worked for me. Just inject this controller in app module.

import { Controller, Get, Req, Res } from '@nestjs/common';@Controller('uploads')export class ServeFilesController {    @Get('products/images/:imageName')    invoke(@Req() req, @Res() res) {        return res.sendFile(req.path, { root: './' });    }}