How to serve static HTML files in Nest.js?
For serving static files you have to use useStaticAssets()
instead of setBaseViewsDir()
:
app.useStaticAssets(join(__dirname, '../../client/dist'))
When you use useStaticAssets
you don't need to set up a controller, all your files will be served automatically:
Let's say under client/dist
you have the files index.html
and pic.jpg
.They will be served as:
localhost:3000 -> index.htmllocalhost:3000/pic.jpg -> pic.jpg
Setting the base views dir is needed when you want to use a view engine like for example hbs
, see docs.
Regarding the official documentation of Nest.js one should serve static files like this:
Install the required package:
npm install --save @nestjs/serve-static
Update app.module.ts to look like this:
import { Module } from '@nestjs/common';import { AppController } from './app.controller';import { AppService } from './app.service';import { ServeStaticModule } from '@nestjs/serve-static';import { join } from 'path';@Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'client'), // <-- path to the static files }), ], controllers: [AppController], providers: [AppService],})export class AppModule {}
If you have something like this
/public |-index.html |-main.js |-etc./src |-app.controller.js |-app.module.js |-main.js
In main.ts or main.js
async function bootstrap() { const app = await NestFactory.create(AppModule); app.useStaticAssets(join(__dirname, '..', 'public')); app.setViewEngine('html'); await app.listen(5000);}bootstrap();
In app.module.js
@Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'public'), exclude: ['/api*'], }), ], controllers: [AppController], providers: [AppService],})export class AppModule {}
In app.controller.js
@Controller()@Dependencies(AppService)export class AppController { constructor(appService) { this.appService = appService; } @Get() @Render('index') root() { }}
With this code, you can do the trick :) :) :)