Generate standalone output of your Next.js app and deploy through pm2

Generate standalone output of your Next.js app and deploy through pm2

References

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

Issues