nestjs / serve-static

Serve static websites (SPA's) using Nest framework (node.js) 🥦

Home Page:https://nestjs.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Serve asset files

0xC0DEBA5E opened this issue · comments

I have a question regarding the purpose of this module:

Can I use this module to serve static assets like images, videos and other miscellaneous files?

With the provided example every request maps to an index.html file inside the rootPath and I wasn't able to figure out a way to access any other file within the rootPath.

Am I missing something?

@0xC0DEBA5E According to my understanding, this module is for providing an out-of-box solution for serving Single Page Applications with a built index.html, among other static assets. It's aggressively overriding / (or the URL at options.renderPath), and always looking for index.html (and if missing, throws an exception). So it's more for fully-static sites than just for static assets.

If you just want to serve some static assets (like images, CSS, etc) and not an entire SPA, I would advise you to not use this module, but a more simplistic approach, like this:

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import * as path from 'path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useStaticAssets(path.join(__dirname, '..', 'public'));
  await app.listen(3000);
}

bootstrap();

At least this is what I'm using, and it works perfectly. Let me know if you need any more help!

I am wondering what's the difference between this module and useStaticAssets under the hood?
And is there any drawback if I use this module to serve static assets like images and videos instead of useStaticAssets method?