Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 42 ยท Building Real APIs

Server-Side Views and Static Files

Serve HTML from NestJS: set up a view engine with Handlebars, return data with @Render, escape output safely, and serve CSS, images and a built SPA with useStaticAssets and ServeStaticModule.

Nest is famous for JSON APIs, but it was designed after the classic MVC frameworks, and it can render HTML pages too. That is useful for admin panels, e-mail previews, landing pages, documentation sites and small internal tools, places where a separate front-end project would be overkill. It is also how people coming from Express with a view engine (or from Laravel and Rails) first feel at home.

In this lesson you will set up a template engine, return a view from a controller with @Render, understand how templates escape output, and serve static files (CSS, images, a built single-page app). The Nest code is read-only because it needs npm. The stand-ins are real in the parts that matter: a tiny template renderer with escaping, and a loopback server that serves static files with protection against path traversal.

MVC in Nest

MVC means Model, View, Controller. In Nest the controller is the class you already know, the model is whatever your services return, and the view is a template file that turns that data into HTML:

TEXT
request -> controller -> service (model data) -> template (view) -> HTML response

Nest does not include its own template language. It lets you plug in an Express-compatible view engine (on the Express platform) such as Handlebars (hbs), Pug or EJS. On Fastify the equivalent is @fastify/view. This lesson uses Handlebars and the Express platform.

Setting up a view engine

Install hbs, then configure the app in main.ts with NestExpressApplication:

TypeScript
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'node:path';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  await app.listen(3000);
}
bootstrap();

Three calls do the work: useStaticAssets serves a folder of files as-is, setBaseViewsDir says where templates live, and setViewEngine('hbs') picks the engine. Put templates in views/ and make sure your build copies views/ and public/ next to the compiled code (the Nest CLI's nest-cli.json has an assets option for exactly this; forgetting it is the classic "works in dev, Failed to lookup view in production" bug).

Returning a view with @Render

A handler decorated with @Render('index') does not return JSON. The object it returns becomes the template data:

TypeScript
import { Controller, Get, Render, Query } from '@nestjs/common';

@Controller()
export class PagesController {
  constructor(private readonly products: ProductsService) {}

  @Get()
  @Render('index')
  async home(@Query('q') q?: string) {
    const items = await this.products.search(q);
    return { title: 'Shop', query: q ?? '', items, count: items.length };
  }
}

The matching template views/index.hbs:

HANDLEBARS
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>{{title}}</title>
  <link rel="stylesheet" href="/css/site.css">
</head>
<body>
  <h1>{{title}}</h1>
  <p>{{count}} products{{#if query}} for "{{query}}"{{/if}}</p>
  <ul>
    {{#each items}}
      <li>{{name}}: {{price}}</li>
    {{/each}}
  </ul>
</body>
</html>

{{name}} prints a value, {{#if}} and {{#each}} give you conditions and loops. Pug uses indentation instead of tags and EJS embeds JavaScript, but the controller side is identical: return data, name a view.

If you need dynamic choices (for example a different template per tenant), inject the response and call res.render('name', data) yourself, or return the rendered string. Prefer @Render when it is enough, since it keeps handlers testable: you can unit test the returned data object without any HTML.

Escaping: why {{ }} is safe and {{{ }}} is not

Whatever you print into HTML from user input is a potential cross-site scripting (XSS) hole. Handlebars escapes {{value}} by default: < becomes &lt;, so a product named <script>steal()</script> shows as text. The triple form {{{value}}} prints the raw string. Use it only for HTML you produced and trust, never for user input. Pug and EJS have equivalents (= escapes, != does not; <%= escapes, <%- does not). If you must show user-provided rich text, sanitize it with a library built for that, and combine it with the Content-Security-Policy that helmet can send.

Static files

Static files (CSS, JavaScript, images, fonts) need no logic: the server maps a URL to a file. There are two ways to do it in Nest.

useStaticAssets (shown above) wraps Express's static middleware. You can add a URL prefix so that files do not collide with routes:

TypeScript
app.useStaticAssets(join(__dirname, '..', 'public'), { prefix: '/assets/' });

A request for /assets/css/site.css is answered from public/css/site.css.

ServeStaticModule from @nestjs/serve-static does the same inside the module system, and is the usual way to host a built single-page app (React, Vue, Angular) next to your API:

TypeScript
import { ServeStaticModule } from '@nestjs/serve-static';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'client', 'dist'),
      exclude: ['/api/{*path}'],
    }),
    ApiModule,
  ],
})
export class AppModule {}

The exclude list tells the static handler to leave API routes alone. Without it, a single-page app's "fallback to index.html for unknown paths" rule would swallow your API's 404s. (The wildcard syntax in exclude changed with the path-to-regexp upgrade in recent Nest versions, so check the package's guide for yours.)

What static serving needs to get right

  • Path traversal. GET /assets/../../.env must never read files outside the root. The built-in middleware protects against it, but if you ever write your own file endpoint, resolve the path and check that it stays inside the base directory.
  • Caching. Fingerprinted files (app.3f9a1c.js) can have Cache-Control: public, max-age=31536000, immutable. HTML should not be cached for long.
  • Compression and CDN. In production, let nginx or a CDN serve static files; Node should not spend its single thread on downloading images. Serving them from Nest is perfect for development, small sites and internal tools.
  • Dotfiles and uploads. Never serve a folder that contains secrets, and never serve an uploads folder as executable content (see File Uploads).

Stand-in: a template renderer with escaping

The stand-in below is a miniature of what hbs does: variables with HTML escaping, a raw form, {{#if}} and {{#each}}. It is not Handlebars (which is far richer), but it makes the escaping rule visible. The "controller" returns plain data, exactly like a @Render handler.

Node.js A tiny template engine that escapes by default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The malicious product name and search text appear as harmless entities (&lt;script&gt;), while the footer that we marked as trusted keeps its <em>. That difference between {{ }} and {{{ }}} is the whole XSS story for server-side templates.

Stand-in: a static file server that blocks traversal

This stand-in is a real loopback server that serves files from an in-memory "public folder" with proper content types and cache headers, and refuses paths that try to leave the root. An in-memory map stands in for the disk (the sandbox has no files of its own), but the path normalization is the real security logic you would apply to disk paths.

Node.js Static files, content types and path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The two traversal attempts (one encoded, one with literal ..) are refused with 403 before any file lookup, and the secret never leaves secrets. Note that http.get is used instead of fetch, because fetch collapses .. segments in the URL before sending, which would hide the attack.

Choosing between views and a separate front end

Server-rendered Nest views are a good fit when pages are mostly content, when SEO matters and there is no heavy interactivity, or when a quick internal tool needs a UI today. A separate front end (React, Vue or Angular, talking to a Nest JSON API) fits highly interactive applications and teams that split front-end and back-end work. Nothing stops you from mixing both: Nest serves the API under /api, the built SPA from ServeStaticModule, and a few server-rendered pages for things like password-reset e-mails and admin screens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a handler decorated with @Render('index') return?

    The returned object is passed as the data to the view engine, which renders views/index.* into HTML.
  2. 2. A product name contains <script>. Which Handlebars syntax prints it as harmless text?

    Double braces HTML-escape the value. Triple braces print it raw and should only be used for trusted HTML.
  3. 3. What is ServeStaticModule most often used for?

    It serves static content as part of the module system, and exclude keeps API routes from falling through to index.html.
  4. 4. Why does a project that renders views fine in development fail with 'Failed to lookup view' in production?

    The build only compiles TypeScript. Template and public folders must be copied, for example with nest-cli.json assets.
  5. 5. How should a custom file-serving endpoint protect against GET /files/../../.env?

    Normalize and check the final path against the root, and reject anything outside it.

Summary

  • Nest can render HTML: set a view engine (setBaseViewsDir, setViewEngine('hbs')), then return data from a handler with @Render('view').
  • Templates escape {{ value }} by default; raw output ({{{ value }}}) is only for trusted HTML, since it is the XSS hole.
  • useStaticAssets and ServeStaticModule serve CSS, images and built SPAs; use exclude to protect API routes and a prefix to avoid route collisions.
  • Static serving must prevent path traversal, set sensible cache headers, and in production usually belongs to nginx or a CDN.
  • Copy views/ and public/ into the build output, or production will not find them.

Next, return to the big picture and compare Nest with Express and Fastify in What is NestJS?.