Generate standalone output of your Next.js app and deploy through pm2
References
- https://nextjs.org/docs/pages/api-reference/config/next-config-js/output
Set Next.js to output standalone
// next.config.mjs located in the same directory as package.json
// *** START: Export a DEFAULT object, i.e nextConfig
const nextConfig = {}
// Produce standalone output
// ---------------------------------
// "next start" doesn't generate standalone output.
// Generate standalone output if BUILD_STANDALONE=true.
nextConfig.output = process.env.BUILD_STANDALONE === "true" ? "standalone" : undefined;
// *** END: Export
export default nextConfig;
Build & deploy
Run build to generate standalone directory
export BUILD_STANDALONE=true
npm run build
#\cp -a data .next/standalone/ # For other file. e.g. myDb.sqlite
\cp -a public .next/standalone/
\cp -a .next/static .next/standalone/.next/
Run
nextjs_port=4666
export PORT=${nextjs_port}
node .next/standalone/server.js
Or, deploy using pm2
nextjs_app_name="openwritings.net"
nextjs_port=4666
# Remove entry if it already exists.
pm2 stop ${nextjs_app_name} || true
pm2 delete ${nextjs_app_name} || true
# Run & deploy using pm2
export PORT=${nextjs_port}
pm2 start node --name ${nextjs_app_name} -- .next/standalone/server.js
# Save it so after computer reboot, it will automatically run.
pm2 save
Ignore .next/standalone directory
- Ignore thousands of files in
.next/standalone
directory.
# DoesnΒ΄t work.
git rm -r --cached .next/standalone
git commit -m "Ignore Next.js standalone output"
git push
// ~/.config/Code/User/settings.json
{
"files.exclude": {
"**/.next/standalone": true
},
"search.exclude": {
"**/.next/standalone": true
}
}
Issues
- Error such as "File not found" or "Sqlite database file not found".
- This is likely you pass a full path or a relative path where your file is not found under
./standalone/
directory. - The solution that I'm proposing is:
-
For all your file paths, use relative path to the ROOT directory of your Next.js app.(
<Next_ROOT_DIR>/package.json
) -
./standalone/
directory becomes the<Next_ROOT_DIR>
directory. -
Therefore, copy your files under
./standalone/
directory. -
Example: my
./data/
is copied to./standalone/
data/ βββ _empty_db.txt βββ rampricesdeal.db βββ _readme.sh package.json #... .next/standalone/data βββ _empty_db.txt βββ rampricesdeal.db βββ _readme.sh
-
- This is likely you pass a full path or a relative path where your file is not found under