Nest, by default, makes use of the Express library under the hood. Hence, every technique for using the MVC (Model-View-Controller) pattern in Express applies to Nest as well.
First, let's scaffold a simple Nest application using the CLI tool:
$ npm i -g @nestjs/cli
$ nest new project
In order to create an MVC app, we also need a template engine to render our HTML views:
$ npminstall --save hbs
We've used the hbs (Handlebars) engine, though you can use whatever fits your requirements. Once the installation process is complete, we need to configure the express instance using the following code:
In this code, we are specifying the template to use in the @Render() decorator, and the return value of the route handler method is passed to the template for rendering. Notice that the return value is an object with a property message, matching the message placeholder we created in the template.
While the application is running, open your browser and navigate to http://localhost:3000. You should see the Hello world! message.
If the application logic must dynamically decide which template to render, then we should use the @Res() decorator, and supply the view name in our route handler, rather than in the @Render() decorator:
info Hint When Nest detects the @Res() decorator, it injects the library-specific response object. We can use this object to dynamically render the template. Learn more about the response object API here.
As mentioned in this chapter, we are able to use any compatible HTTP provider together with Nest. One such library is Fastify. In order to create an MVC application with Fastify, we have to install the following packages:
$ npm i --save fastify point-of-view handlebars
The next steps cover almost the same process used with Express, with minor differences specific to the platform. Once the installation process is complete, open the main.ts file and update its contents:
The Fastify API is slightly different but the end result of those methods calls remains the same. One difference to notice with Fastify is that the template name passed into the @Render() decorator must include a file extension.