node.jsdeploymentnext.jsshared-hosting

Deploy Next.js to Shared Hosting


I need to deploy a Next.js App to a shared hosting provider that supports Node.js. The official Next.js documentation says you (only?) need to run next start (via SSH I guess) on the server.

  1. Do I need to deploy the build version only or do I need to run the build command on the server via ssh?
  2. Is running npm start really the only thing I need to do once the build is ready? I am a bit afraid that the server stops for whatever reason and the site goes down. I googled quite a bit and found some people mentioning using pm2 (Referring to this article on freeCodeCamp.) But not sure if Next.js maybe restarts the server automatically when in production?

Solution

  • On the server, you can do like this, and of course you should have pm2 (npm install -g pm2) and config for nginx to proxy pass the port that your next server will run, e.g 6060 (add to nginx.conf/server/location this line: proxy_pass http://localhost:6060) and then:

    1. upload source folder (pages, public, src , package.json) - e.g your-folder to somewhere like /var/www/your-folder
    2. chown it: sudo chown -R $USER:$USER /var/www/your-folder
    3. cd to your-folder and run: npm -i
    4. then edit package.json and change "next start -p your-port" e.g 6060
    5. npm run build
    6. run pm2 (in your-folder) : pm2 start "npm run start" --name project-whatever-you-like

    For pm2 to auto-restart you run: pm2 startup systemd , pm2 will produce a line and you should copy that line and run it.

    On shared hosting there's a lot providers now support running nodejs app, but I dont know if they can run nextjs app, e.g in plesk you can config to run nodejs app by configuring app.js path and project folder path, public folder path etc, but for next app, you dont have an app.js to run, but a script to start next server. Anyway you can try :)

    Or you can simply move to a vps, its price is now rather bargain, and you can do a lot of things with your own server (Google Compute Engine is giving free stuff - almost free for a year)