'How to run nrwl/nx production build of web app on localhost (NextJS)
Is there a way to run nrwl/nx next.js built app for production on localhost?
I tried using npm i -g serve
and after serve -s
in the folder of the next app, but the app appears without styles and navigation.
It seems that only index.html is present.
Do I have to use Vercel to deploy or is there a way to just test the performance of the bundled app on localhost?
Solution 1:[1]
You need a custom server for this. Create a server.js file in the root directory of your project. It should look like this:
const express = require("express");
const next = require("next");
const PORT = parseInt(process.env.PORT, 10) || 3364;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => handle(req, res));
server.listen(PORT, err => {
if (err) throw err;
console.log(`? => Ready on http://localhost:${PORT}`);
});
});
Then make sure that your package.json has these scripts:
{
"scripts": {
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
Then you just have to build the app with npm run build
and then start the app with npm run start
.
next build builds the production application in the .next folder. After building, next start starts a Node.js server that supports hybrid pages, serving both statically generated and server-side rendered pages.
Read more about it here.
UPDATE: Added the correct start script.
Solution 2:[2]
EDIT:
You can also run custom commands with your custom server file. The official documentation is here.
"production": {
"executor": "@nrwl/workspace:run-commands",
"options": {
"command": "node apps/web/server.js"
}
},
1) STATIC WEBSITE
From the official documentation:
Then, run next build to build your application. Finally, run next start to start the Node.js server. This server supports all features of Next.js.
That means that in NX
you want to build your project:
nx build project-name
Then navigate to dist
folder:
cd dist/apps/project-name
Then you can run your project:
npm run start
2) SSR WEBSITE
Gh05d is kind of correct and if you want to run Next in SSR mode then you have to create a custom server file. You can find documentation how to do that here and then the rest of your setup is gonna depend on where and how do you want to deploy your application.
If you are working on a demo application or if your company uses Vercel then you can deploy your application to Vercel without custom server.js
files.
Here is the official NX documentation:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |