Skip to content

Instantly share code, notes, and snippets.

@twhid
Last active February 19, 2021 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twhid/fcac591859718115636d8a570863fc4b to your computer and use it in GitHub Desktop.
Save twhid/fcac591859718115636d8a570863fc4b to your computer and use it in GitHub Desktop.
Start Next.js if behind passenger
// I found bad advice online on how to use Next.js behind passenger https://www.phusionpassenger.com/
// yarn start or npm start won't work. This file is derived from the code that runs when you
// run the yarn start command. Tested only in my particular setup where the file is required
// to be called app.js. This file is TS, so you'll need to transpile to JS in your build,
// eg change package json build script to (you'll need a tsconfig.server.json file):
// "build": "next build && tsc --project ./tsconfig.server.json",
import http from 'http';
import next from 'next';
async function start(opts: any, port?: number, hostname?: string) {
const app = next({ ...opts, customServer: false });
const srv = http.createServer(app.getRequestHandler());
await new Promise<void>((resolve, reject) => {
// This code catches EADDRINUSE error if the port is already in use
srv.on('error', reject);
srv.on('listening', () => resolve());
srv.listen(port, hostname);
});
// It's up to caller to run `app.prepare()`, so it can notify that the server
// is listening before starting any intensive operations.
return app;
}
const port = parseInt(process.env.NODE_PORT, 10) || 8888;
const host = process.env.NODE_HOST || '0.0.0.0';
const dev = process.env.NODE_ENV === 'development';
const dir = '.';
start({ dir, dev }, port, host)
.then(async (app) => {
// eslint-disable-next-line no-console
console.log(`started server on ${host}:${port}`);
await app.prepare();
})
.catch((err) => {
console.error(err);
process.exit(1);
});
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"isolatedModules": false,
"noEmit": false
},
"include": ["app.ts"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment