By default, Next.js includes its own server with next start
. If you have an existing backend, you can still use it with Next.js (this
is not a custom server). A custom Next.js server allows you to start a
server 100% programmatically in order to use custom server patterns. Most of
the time, you will not need this - but it's available for complete
customization.
To create a custom server and deploy it to cpanel, follow the steps below:
server.js
in the root of your
project directory.
// You can find this code in the Next.js docs here:
// https://nextjs.org/docs/pages/building-your-application/configuring/custom-server
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer(async (req, res) => {
try {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === "/a") {
await app.render(req, res, "/a", query);
} else if (pathname === "/b") {
await app.render(req, res, "/b", query);
} else {
await handle(req, res, parsedUrl);
}
} catch (err) {
console.error("Error occurred handling", req.url, err);
res.statusCode = 500;
res.end("internal server error");
}
})
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});
package.json
file:
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
Run npm run build
to build your app.
Make a archive of your project files eg. portfolio.zip
. (Exclude node_modules
folder, otherwise it
will take a lot of time to upload)
(eg. public_html)
.
(eg. https://example.com)
.
(server.js)
in our case.
(eg. public_html)
(cPanel >> Home >> SOFTWARE >> Setup Node.js
App)
.
This is it. Now you can visit your website and see the magic. To view the
logs, open file manager and naviate to folder where you uploaded your
project files. There you will find a file
named stderr.log
. Open it and you will see the logs.
Subscribe to our newsletter to receive the latest news and updates about our services and products.