Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve static HTML files in Nest.js?

I want to serve static HTML files which are in a /dist folder outside of the Nest project. index.html is loaded successfully but it fails to load any JS file (404 error).

I have a Node/Express.js project which uses

app.use('/', express.static('../client/dist'))

and it works perfectly fine.

In the Nest project, however,

app.setBaseViewsDir(join(__dirname, '../../client/dist'))

does not do the trick.

In the AppController I tried

import { Response } from 'express';

@Get()
  get(@Res() res: Response) {
    res.sendFile('index.html', {
      root: '../client/dist',
    });
  }

But no luck.

As mentioned, the index.html is loaded successfully. So the problem is not a wrong path. Neither is the problem wrong src-paths in the index.html because in the Express project the exact same files are used.

/dist
  |-index.html
  |-main.js
  |-etc.

In the index.html:

<script type="text/javascript" src="main.js"></script>

It does not work either when I put the dist folder into the Nest project (and adapt the path).

I found the solution:

I use the express module now:

import * as express from 'express';
...
app.use('/', express.static('../client/dist'));
like image 662
Maurice Wipf Avatar asked Mar 24 '19 14:03

Maurice Wipf


Video Answer


2 Answers

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.html
localhost: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.

like image 110
Kim Kern Avatar answered Sep 16 '22 14:09

Kim Kern


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 {}
like image 32
Philipp Kief Avatar answered Sep 20 '22 14:09

Philipp Kief