Do not build your Node app on a 1 GB server
The smallest cloud servers have 1 GB of memory. That is plenty to serve a Node app with a Postgres database next to it. It is often not enough to build one: installing a few hundred packages and running a TypeScript and Vite build on the same machine can use all of it, and then the kernel stops the process halfway. This site runs on such a server, and the server never builds anything.
The idea
Build on the machine that has memory, which is the one on your desk. Copy the result. The server only runs it.
For that to work, the server must not need npm install either. So the server code is bundled into a single file together with its dependencies.
Bundle the server into one file
The client is built by Vite as usual. The server is built by esbuild:
await esbuild({
entryPoints: ["server/index.ts"],
platform: "node",
bundle: true,
format: "cjs",
outfile: "dist/index.cjs",
minify: true,
external: externals,
});
Here externals is every package that is not on a short list of runtime dependencies (express, pg, stripe and so on). Everything on the list is compiled into dist/index.cjs. The result is one file of server code and one folder of static files. There is no node_modules folder on the server at all.
A side effect: the app starts faster, because Node opens one file where it used to open thousands.
Packages with native binaries cannot be bundled this way. If you depend on one, keep it external and install only that package on the server.
The deploy script
The whole deploy is a shell script of about thirty lines. Its core:
npm run build
rsync -az --delete dist/ server:/var/www/app/dist/
ssh server 'systemctl restart app && sleep 2 && systemctl is-active app \
&& curl -fsS -o /dev/null http://127.0.0.1:5000/ \
&& nginx -t && systemctl reload nginx'
Build, copy, restart, check that the service is active, check that the app answers on its local port, then reload nginx. If any step fails, the script stops and says so.
Three traps we hit
- An environment file for systemd is not a shell file. We tried to source it in the deploy script to get the database address, and a password with shell characters broke the script. Read the one key you need with grep and cut.
- rsync --delete removes from the server everything that is not in your build. That is what you want, until the build is wrong. A cloud-sync app once renamed 26 icon files in our project folder, the build copied the new names, and the deploy deleted the originals from the live site.
- A build on your own machine uses your own Node version. Keep the same major version on the server, or the bundle may use something the server does not have.
Read: how a deploy removed 26 icons from our live site
When to build on the server after all
If several people deploy, the build belongs in a pipeline, so everyone ships the same result. For one developer and one small server, building locally is the shortest path, and the server stays small.