ยท hands on
Serving static content with NestJS and Express
NestJS can serve static content when running on an Express server. This is useful when you want to host a React frontend website through your Nest service.
Nest is a versatile framework that works with Fastify or Express web servers. When it's running on an Express server, you have the convenience of serving static content. This becomes especially valuable when you intend to bundle a React web page and host it through your Nest service.
When you're building a Nest backend, it's not limited to merely providing REST endpoints. It can also serve as the host for a frontend website. Nest offers the serve-static package to handle such situations. However, if your Nest framework is powered by an Express application under the hood, you have the option to serve static content using the response.sendFile API from Express.
Return static content with Nest Controller
Consider a controller that serves static content by returning a string:
This can be replaced by specifying the file path to a static HTML page and utilizing the "sendFile" method:
Note that the Response
type from Express is being used here.
Host static directory
If your intention is to host more than just a basic HTML page, such as CSS or JavaScript files that you need to reference, it's recommended to declare the entire directory for hosting purposes:
In this case, you can remove the routing from the Nest controller.