If you are developing a web app with Nest.js as the backend. And now, you want to deploy your whole app into a single server. Then you may run into a problem of serving static assets. Especially if your frontend is a SPA. Fear not, there are multiple ways to achieve this, so how to serve static files with NestJS?
In short, we achieve this by using the
express.static method inside our Nest App. And pass the assets folder to our method params.
Serve Static Files with NestJS
Serving the static files is straightforward. We just have to use express which comes out of the box with Nest, inside our main.ts file where we initialize our app:
Now all the files, when requested from our server will be sent back correctly. There is one more thing though, which is our HTML page.
If you’re building a single page application you will usually have a single HTML page and then rely on your frontend framework to do the routing. In that case, we need a way to always return that HTML page from our server no matter which route is being requested with the single exception of our API route. Let’s find out how to do it.
Serve Main HTML File Using a Controller
The controller approach is pretty straightforward, we will use or create an
AppController that will have a
Get handler, this handler will use a wildcard route, and all we have to do is return our HTML page:
We also have to check if the requested route is our API. In that case, we need to return next so that Nest can handle that route and return the appropriate result.
Serve Main HTML File Using a Middleware
Using a middleware is a cleaner approach. Since Nest is built on top of express, we can leverage the middleware feature to run code that can be executed before our route handlers.
What is a middleware
Looking at this picture from the official docs, a middleware is something that sits between the request interception and route handling, thus we can leverage it to serve our static files without hitting the route handler at all.
Using a middleware
We can start by creating our middleware, we will call it
app.middleware.ts, inside the middleware, we will just do the same check we did inside our controller earlier:
Now we have to register this middleware inside our main app, and only trigger it when we have a get request to any route, so inside app.module.ts we will do:
Nest.js is a great framework, and combining it with a good frontend library/framework will make a perfect combination. Hopefully, after reading this tutorial, you got this working in your app.
I write code to solve real-world problems and build business applications as a Full-Stack developer. I enjoy being challenged and develop projects that require me to work outside my comfort and knowledge set. I’m interested in engineering, design, entrepreneurship, and startups. When driven by passion, making stuff is just fun.