Aller au contenu

Migrating a Next.js application to the Node.js Selector in cPanel

Ce contenu n’est pas encore disponible dans votre langue.

The Node.js Selector in cPanel allows you to run Node.js applications directly from your hosting account. If you already have a Next.js application, you can migrate it to the Node.js Selector with a few adjustments to ensure compatibility.

Preparing Your Next.js Project for Migration

Section titled “Preparing Your Next.js Project for Migration”
    • Make sure you have Node.js (v18.17 or higher) and npm installed on your development machine.
    • If starting fresh:

      npx create-next-app@latest
    • If you already have a project, skip this step.

    • In your project root, create a file named server.js.

    • Example:

      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;
      const app = next({ dev, hostname, port });
      const handle = app.getRequestHandler();
      app.prepare().then(() => {
      createServer(async (req, res) => {
      try {
      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');
      }
      }).listen(port, () => {
      console.log(`Ready on http://${hostname}:${port}`);
      });
      });
      Update package.json
    • Replace the start script with:

      "start": "NODE_ENV=production node server.js"
npm run build
zip -r ../nextapp.zip . --exclude ".git/*" .gitignore "node_modules/*" README.md
    • Log in to cPanel.
    • Use File Manager to upload nextapp.zip to your account.
    • Extract it into public_html/nextapp.
    • Go to Tools → Software → Setup Node.js App.
    • Click Create Application.
    • Select the Node.js version (must be ≥ 18.17).
    • Set Application Mode to Production.
    • Set Application Root to nextapp.
    • Set Application Startup File to server.js.
    • Click Create.
    • Click Run NPM Install in the Node.js Selector interface.
    • Wait for installation to complete.
    • Click Start App.
    • Visit your domain (e.g., example.com) to confirm the Next.js app is running.

Cette page vous a-t-elle aidé ?