How to Deploy a Next.js App Router Project on Node.js Supported cPanel

How to Deploy a Next.js App Router Project on Node.js Supported cPanel

Deploying a Next.js project using the App Router on a Node.js supported cPanel can be straightforward if you follow these steps. This guide will help you get your application up and running smoothly.

Step 1: Create a Custom Server

First, set up a custom server for your Next.js app. Create a server.js file in the root directory of your project with the following code:

import { createServer } from "http";
import { parse } from "url";
import next from "next";

const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url!, true);
    handle(req, res, parsedUrl);
  }).listen(port);

  console.log(
    `> Server listening at http://localhost:${port} as ${
      dev ? "development" : process.env.NODE_ENV
    }`,
  );
})

Step 2: Update package.json

Modify the scripts section in your package.json to include:

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "NODE_ENV=production node server.js"
}

Step 3: Build Your Application

Run the following command to build your Next.js app:

npm run build

Step 4: Upload Files to cPanel

Compress your project files (excluding node_modules) into a .zip file. Log in to your cPanel account and navigate to the File Manager. Upload the .zip file to your desired directory and extract it.

Step 5: Set Up Node.js Application

  • In cPanel, go to the Setup Node.js App section.

  • Create a new application, set the application root to the directory where you uploaded your files, and specify the startup file as server.js.

  • Install the necessary dependencies by running :

References

Next.js Documentation: The official Next.js documentation provides comprehensive guides on setting up and deploying Next.js applications. You can find more details here. documentation

By following these steps, you can successfully deploy your Next.js App Router project on a Node.js supported cPanel. This guide ensures a smooth setup process, from creating a custom server to configuring your application in cPanel. With these instructions, you can confidently get your Next.js application up and running, leveraging the powerful features of both Next.js and cPanel. If you encounter any issues or need further assistance, refer to the official Next.js documentation or seek additional help. Happy deploying!