How to serve static HTML files in Nest.js?

Maurice Wipf picture Maurice Wipf · Mar 24, 2019 · Viewed 10.9k times · Source

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'));

Answer

Kim Kern picture Kim Kern · Mar 24, 2019

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.