Home ยป How to Serve React/SPAs in Nestjs

How to Serve React/SPAs in Nestjs

Nestjs serve static content
Share this post:

With NestJs we can serve static content such as Single Page Applications (SPAs) – React js, NextJs, Vue, etc.

To make serving static content easier, Nest js has a package @nestjs/serve-static which gives us a module we can import and configure to serve our frontend apps.

Serving a React (or SPA) App in Nest Js

First, you need to set up a Nest js project. After that, install the package we’ll use to accomplish the task: npm install –save @nestjs/serve-static

With the package installed, head over to AppModule to add and configure ServeStaticModule in the imports:

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'client'),
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Configuration

rootPath: specifies the path to the frontend SPA app. In this case, we pointed to a folder named “client” (you’re free to choose any folder name/path).

It means that at the root of the Nestjs project we should have a folder named “client”. This client folder will contain our React app.

other options: You may take a look at the package for other configurations that might be applicable to your project.

The React (or SPA) App

With Nest js configured to serve our front end, we need to build our React App and move the content of the resulting “build” folder into the “client” folder in our Nest Js project.

Important: If Nest js route coincides with the client app route Nest js route will be served. To resolve the conflict, you can prefix your NestJs routes with, for example, “api”:

  • NestJs API: Example: localhost:5000/api/users
  • Frontend app URL: localhost:5000/users

Learn More

You can learn more about serving content like a Single Page Application (SPA) on NestJs from the official documentation. There is also a section on attaching global prefixes to routes in Nest.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.