Introduction
In this article, we will explain how to use the monorepo tool Nx to serve a statically generated site created with Next.js SSG (Static Site Generation) from a Next.js application. This approach allows you to have both the frontend and backend in a single project.
1. Create Frontend and Backend Projects
Create Nx Workspace and Nestjs Project
Navigate to the desired directory and run the following command:
This will create the Nestjs api
project.
Create a Nextjs Project
The directory structure created by the above commands will look like this:
2. Enable Nextjs (Frontend) for SSG (Static Site Generation)
To enable support for static files, make the following changes:
- Add
unoptimized: true
inimages
(SSG doesn't supportnext/image
). - Add
output: 'export'
. - Add
trailingSlash: true
.
If you don't set
trailingSlash: true
, when accessing Nextjs via Nestjs, reloading the browser on pages other than the homepage will redirect you to the homepage.
3. Add ServeStaticModule to Nestjs (Backend)
Import the serve-static
Package
Implement the ServeStaticModule
With the above code, if the endpoint does not start with /api
, it will redirect to the .next
directory, which is the static site of Nextjs.
At this point, the
.next
folder has not been generated yet. It will be generated later when you run Nextjs Build, as explained below.
4. Add Build and Start Commands to package.json
Add the build and start commands to your package.json
file.
Next, execute the build command:
This will generate build files for both the frontend (web) and backend (api).
Finally, execute the start command:
This will start the backend server on localhost, and you can access the Next.js pages in your browser.
By deploying these, you can serve both the frontend and backend integrated on a single server.
For reference, here is the directory structure after the build: