Best way to host a Node.js app

For bots, WebSockets and APIs with steady traffic, the best option is an always-on container, on a hosting platform or a VPS. Serverless fits webhooks and short tasks with irregular traffic.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Know which criteria decide where to host a Node.js app
  • Compare a VPS, a container platform, serverless and orchestration
  • Prepare your code to run well on any of them
On this page

There is no single right place to host Node.js. A Discord bot, a REST API, a Next.js site and a webhook that gets ten calls a day have different needs, and the wrong choice shows up as an offline bot, timeouts, a high bill or weekends spent patching a server.

The decision gets easier when you start from criteria, compare the four most common ways to host Node.js and land on a recommendation per scenario. If you have already chosen and want the step-by-step, see how to host a Node.js app.

Does the processneed to stay on?YesContainerbots, APIs,WebSocketswho runs the server?Platformno OSto maintainVPSyou runthe serverNoServerlesswebhooks,short jobsDuration limitper run
A process that stays on goes in a container, on a platform or a VPS; a short task fits serverless, within the duration limit.

Which criteria decide where to host Node.js?#

Five questions settle most cases:

  1. Does the process need to stay on all the time? Gateway bots, WebSocket servers, queues and jobs scheduled inside the app need a continuous process. An API that only answers requests does not, but it runs fine that way too.
  2. Are there persistent connections? WebSockets, Server-Sent Events and long-lived database connections need a process that is not destroyed between requests.
  3. Who will run the server? Patching the system, configuring a firewall, renewing certificates and restarting the process after a crash takes work, and someone has to do it.
  4. What does traffic look like? Steady traffic favors fixed capacity and predictable cost. Rare, spiky traffic favors paying per use.
  5. How do you want to deploy? File upload, git push, a CLI, a CI pipeline. Fewer manual steps means fewer mistakes.

Add to these the memory your app uses (see how to size RAM and CPU) and the distance to your users and your database.

What are the options for hosting Node.js?#

VPS#

A VPS is a virtual machine with root access. You install Node.js, upload the code, run a supervisor that restarts the process and put a reverse proxy (such as nginx) in front for TLS. With PM2, for example, the basic flow is:

bash
npm install -g pm2
pm2 start index.js --name api
pm2 save
pm2 startup

pm2 save records the process list and pm2 startup generates the script that restores it after a reboot (it prints a command for you to run with sudo). More in PM2 and auto-restart.

Pros: full control, any software, fixed cost. Cons: security, updates, backups, logs and TLS are on you. See what a VPS is and how much a VPS costs.

Container hosting platform#

You upload the code (ZIP, Git or CLI), set the start command and environment variables, and the platform runs the process in an isolated container. There is no operating system to maintain, and auto-restart, logs and HTTPS usually come ready.

Pros: deploy in minutes, always-on process, less maintenance. Cons: less control over the system (no root, or root limited to the container), and each platform has its own rules for ports, memory and builds. The difference between the models is in VPS, cloud or hosting platform.

Serverless#

You ship functions, and the provider creates an environment for each request or event. The number of environments follows demand, down to zero. In exchange, there are limits: a standard AWS Lambda function runs for at most 15 minutes per invocation, the synchronous payload has a size limit and in-memory state is not reliable between calls. There is also the cold start, the delay on the first call in a new environment.

Pros: no cost at zero traffic, great for rare spikes. Cons: not suited to continuous processes or persistent connections, and the code has to be written as a handler. See serverless or containers.

Orchestration (Kubernetes and similar)#

You describe containers, replicas and network rules, and an orchestrator spreads everything across several machines. It is the choice for teams with many services and people dedicated to running the infrastructure. For one app or one bot, it is complexity with no payoff.

How do the options compare?#

Criterion VPS Container platform Serverless Orchestration
Always-on process Yes Yes No Yes
WebSockets and long connections Yes Yes No (or limited) Yes
Who maintains the system You The platform The provider Your team
Effort for the first deploy High Low Medium Very high
Typical billing Fixed per machine Fixed per resources Per invocation and duration Per cluster machines
Good for Full control, unusual software Bots, APIs, server-rendered sites Webhooks, short jobs Many services, large teams

Which one should you pick for each kind of project?#

  • Discord, Telegram (long polling) or WhatsApp bot: an always-on container, on a platform or a VPS. Serverless does not keep the connection open.
  • REST API with steady traffic: a container platform or a VPS. Predictable cost and no cold start.
  • WebSocket or real-time server: a container. See how to host a WebSocket server.
  • Next.js site with server rendering: a container running next start, or a platform that supports Next.js. See how to host a Next.js app.
  • Webhook or short task with rare traffic: serverless tends to pay off.
  • You want to learn Linux and networking: a VPS. Admin time becomes study, not cost.
  • Several services and an infrastructure team: orchestration.

If you are torn between two options, pick the one that needs less maintenance for your case. Moving later is simple when the code follows the rules in the next section.

What applies on any host?#

A well-prepared Node.js app runs on any of the options above. The points that prevent the most trouble:

  • Use the current Active LTS of Node.js. It gets fixes for the longest; the official release schedule shows which version that is and when each one reaches end of life.
  • Read the port and secrets from the environment. Never hard-code a password or token: use environment variables.
  • Install from the lockfile with npm ci, and keep everything the app imports at runtime in dependencies.
  • Log to stdout, not to files nobody reads.
  • Expose a health route and handle the SIGTERM signal, which hosts and supervisors send before stopping the process.

A minimal server that follows these rules, with no dependencies:

javascript
import http from "node:http";

const port = Number(process.env.PORT) || 3000;

const server = http.createServer((req, res) => {
  if (req.url === "/health") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ status: "ok", uptime: process.uptime() }));
    return;
  }
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
  res.end("Hello from Node.js\n");
});

server.listen(port, () => console.log(`Listening on port ${port}`));

// Shut down gracefully when the platform asks (new deploy, restart)
process.on("SIGTERM", () => {
  console.log("SIGTERM received, closing connections");
  server.close(() => process.exit(0));
});

Save it as index.mjs and run node index.mjs. http://localhost:3000/health should show {"status":"ok",...}. server.close() stops accepting new connections, closes idle ones and calls the callback once in-flight requests finish.

How to do this on Square Cloud#

On Square Cloud, a Node.js app follows the container platform model from the table: each application runs in an isolated, always-on container, with no cold start or sleep mode. Automatic restart is on by default for dashboard deploys and brings back a process that exits with an error, so you do not need PM2. You upload code by ZIP in the dashboard, with the CLI, through GitHub (the official GitHub Action or a webhook) or with the VS Code extension.

The rules from the previous section apply here as well. On start, the platform runs npm install when there is no node_modules, with NODE_ENV=production: packages in devDependencies are not installed, so everything the app imports must be in dependencies. There is no build step, so compile in CI or put the build in the start command. A web app listens on 0.0.0.0, on the port in the PORT variable the platform sets, and whatever you write to stdout shows up in the dashboard's real-time logs. Environment variables take effect on the next restart, with no need to upload the code again.

The plan's RAM is a shared pool: at least 256 MB per background application, such as a bot, and 512 MB per web application. Hobby starts at R$12.49 per month, with 1 GB of RAM and 1 vCPU. There is no autoscaling: you set each application's RAM and, from Standard up, you can spread one domain across several applications with load balancing. Among several runtimes, such as Node.js, TypeScript (with no build step) and Python, see the ones available today on Runtimes and the deployment features on Features.

Deploy

Push from GitHub, the CLI or a ZIP and go live in seconds

Learn more

FAQs

What is the simplest way to put a Node.js app online?

A container-based hosting platform: you upload the code, set the environment variables and the start command, and the platform runs the process. There is no operating system to patch.

Is a VPS worth it for Node.js?

It is if you want full control or want to learn server administration. You install Node.js and set up a supervisor such as PM2 or systemd, the reverse proxy, TLS and security updates yourself.

Can I host a Discord bot on serverless?

Not with the Gateway model, which needs a WebSocket connection open all the time. A standard AWS Lambda function runs for at most 15 minutes per invocation.

Which Node.js version should I use in production?

Use the current Active LTS of Node.js, which gets fixes for the longest. The official Node.js release schedule shows which version is in that phase and when each one reaches end of life.

Next articleBest way to host a Python appThe best way to host Python depends on the app: a bot, a web API, a scheduled job or AI. Compare VPS, containers and serverless, and see when to use each one.

More in Deploy

See all 33 articles