Deploy Next.js to Shared Hosting
Asked Answered
E

4

6

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?
Eightieth answered 11/6, 2020 at 9:45 Comment(0)
A
11

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)

Alleviation answered 20/7, 2020 at 5:0 Comment(1)
This answer suggests uploading the entire development package to the server, which is totally unnecessary. Just upload the folder resulting from the build process. If the app doesn't use nextjs's backend (app.js), it only needs a web server to run. The JS will be compiled either during the build process, or in the client browser.Weekly
P
8

You can find a very helpful discussion here: https://github.com/vercel/next.js/discussions/12234

I found lack of information for deployment to shared hosting with cPanel, so after many trial and errors I hope this would help to those who are straggling with Nextjs deploy to custom server as it reffered in Vercel documentation, and in this case to shared hosting.

  1. Build

From my experience running npm run build on the hosting server, sometimes result in build errors due to limited virtual memory that is provided in shared hosting servers. So, a workaround is simply, perform the build on your local machine and just copy the .next folder created on your machine to the root folder of your project on the hosting server.

  1. Simpler deploy

I did not require 'pm2' nor 'nginx' to run Nextjs project. It was rather straight forward, just copy package.json, 'server.js' and .next to root folder of your project and you're good to go. (see server.js content below)

  1. Server starter file

(you can name it server.js or app.js or index.js or whatever you want, as long as it is consistent with your definition of the Node app in cPanel). here is a minimal required code for the server starter file:

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const dev = process.env.NODE_ENV !== "production";

const port = !dev ? process.env.PORT : 3000;

// Create the Express-Next App
const app = next({ dev });
const handle = app.getRequestHandler();

app
  .prepare()
  .then(() => {
    createServer((req, res) => {
      const parsedUrl = parse(req.url, true);
      const { pathname, query } = parsedUrl;
      handle(req, res, parsedUrl);
      console.log("pathname", pathname);
    }).listen(port, (err) => {
      if (err) throw err;
      console.log(`> Ready on http://localhost:${port}`);
    });
  })
  .catch((ex) => {
    console.error(ex.stack);
    process.exit(1);
  });
Perreira answered 21/1, 2021 at 16:31 Comment(5)
U need to upload and node_modules or run npm i there, but often there are errors just like if you build itNozzle
I tried this, but it runs in development mode. Please, do you know how to run builded version?Neary
Why do you need !dev? Just go const port = dev ? 3000 : process.env.PORT;. It's also customary to do something more like const port = process.env.PORT || 3000. `Cerys
You always need to run the build command before deploying any nextjs or react app. Then all you need for your server is to upload the resulting folder to your host. Create its own folder for it, and then you can direct via your domain using a sub-domain (myapp.mydomain.com) that points to the folder containing index.html in your built folder you uploaded. This is usually done in cPanel (or whatever your shared host's panel type is). You shouldn't have to run npm i.Weekly
The only other thing I'd add, is you want your .htaccess file on your server be configured to recognize the starting file and know to run it as soon as someone lands on the folder. This is why index.html is generally used, because it's universal, and in that file is where you've pointed to index.js (or whatever you decide to name it) as your root div. This MUST be consistent, otherwise you're going to have a bad day.Weekly
W
5

A high-level follow-up: it seems like something is getting lost based on what I've read of the other responses, so let's not lose the forest through the trees.

If your app only uses the front-end portion of nextjs, it should be fine on shared hosting whether the host provides nodejs or not, as the build command makes it deployable on any server that can serve HTML. The JS is then compiled on each client.

If you used nextjs's backend server for your app, that's when you need a compatible version of nodejs running on your host. If you're not using them, it should be fine, because it's basically just like React.

I have deployed several React (CRA) apps to my shared host after build and they all work fine. The host is an aged cheap shared host running cloudlinux 6 (think: Linux kernel ~3.10) and does not provide nodejs backend, only Apache web server.

If they use the backend server (e.g. nextjs's ,app.js), I deploy my nextjs apps to my VPS hosted by HyperExpert - they provide a blank slate OS (mine's Ubuntu 20.04 ATM). It requires you to set up your own proxy server (e.g. nginx) and web server (e.g. lighthttpd, Apache, or nginx can do both) but you have much more flexibility as to what you decide to use.

On a VPS, you can also package your apps as containers via docker, podman, systemd-container, etc. which can help make re-deployment cleaner in the case of updates, and aid in scheduling, such as running your apps as a service and limiting resources.

Important: this is where I think people are getting lost

In either case, you always need to run the build command LOCALLY to prepare your app for deployment.

Then all you need for your server is to upload the resulting folder (e.g. .next) to your host. Create its own folder for it, and you can open mydomain.com/folderyouuploaded in your browser.

Tip: If you name it something without a . in the beginning, it won't be hidden. E.g. run mv .next myappnamev1.0.0 before uploading it.

Most people will also direct via your domain using a sub-domain (myapp.mydomain.com) that points to the folder containing index.html in your built folder you uploaded. This is usually done in cPanel, or whatever your shared host's panel type is.

You should never have to run npm i unless you want to run your app in developer mode (I can't think of a good reason to do this on a host).

If you want to containerize it, it is a bit more involved, but it pays off in the end. With tools like toolbox or if you use a tar.gz systemd-container, you can even edit files inside the container while they're in place, which can certainly be helpful in certain scenarios (think: little tweaks where you'd prefer to avoid an entire re-deployment of your container).

If your app grows large enough, I'd recommend a CI/CD pipeline, but that's beyond the scope of this answer. Good luck!

Weekly answered 2/9, 2022 at 17:7 Comment(1)
thanks for the explanation above. Do you know where I can find a reliable step by step on how to set up a VPS for Next.js? I'm new to backend dev.Arleanarlee
V
4

In your package.json file, you can create:

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "export": "yarn build && next export"
},

and run:

yarn export

than, on the out folder, you can pass via filezila all files, like the image above

enter image description here

to the folder on your Host

Vulnerary answered 24/9, 2021 at 13:1 Comment(3)
I am doing that but getting internal server errorJoy
hey, what version is your next and does your host accept node?Vulnerary
I was getting 500 error because i was also keeping .htaccess file in out folder after deleting that everything works fine, thanksJoy

© 2022 - 2025 — McMap. All rights reserved.