ยท 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:

app.controller.ts
import { Controller, Get } from '@nestjs/common';
 
@Controller()
export class AppController {
  @Get()
  landingPage() {
    return 'online';
  }
}

This can be replaced by specifying the file path to a static HTML page and utilizing the "sendFile" method:

app.controller.ts
import { Controller, Get, Res } from '@nestjs/common';
import { join } from 'node:path';
import { type Response } from 'express';
 
@Controller()
export class AppController {
  @Get()
  landingPage(@Res() res: Response) {
    return res.sendFile(join(`${process.cwd()}/src/static/index.html`));
  }
}

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:

main.ts
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
 
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const staticDirectory = `${process.cwd()}/src/static/`;
app.useStaticAssets(staticDirectory);

In this case, you can remove the routing from the Nest controller.

Back to Blog