In practice
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime. It runs V8, the engine behind Chrome, outside the browser, so JavaScript can work on a server, in a script or in a command-line tool.
An app runs in a single process and does not create a new thread for every request. Reading from the network, a database or a disk is asynchronous: instead of waiting, Node.js comes back when the answer arrives. The main working rule follows from that: one long operation on the main loop holds up every other client.
- Kind
- A runtime environment, open source
- Engine
- V8, as in Chrome
- Working model
- Event loop with non-blocking I/O
- Packages
- npm, the standard manager
How I work with Node.js
I start by asking what the process is meant to do: wait on a database and the network, or calculate. The first kind of work suits Node.js, the second has to leave the main loop. I do not guess it: I check which requests take longest, and only then decide what to move off.
Splitting the work
Database queries, API calls and files stay in the main process. Calculations that take more than a moment go to a worker thread or a separate service, because a blocked loop cannot serve other clients.
One language, one set of types
I write the code in TypeScript and check outside data with a schema where it enters the app. That way one language and the same types cover the frontend and the backend, which is an advantage.
The environment under control
I fix the Node.js version in the project, because on a server I choose the environment and in a browser I do not. I package the app in Docker, so every deployment starts from the same set.
When it fits, and when it doesn't
Node.js fits where the backend mostly waits for data instead of calculating.
A good fit when
- APIs and services that query a database and other systems and have little logic of their own.
- A TypeScript app where the frontend and the backend share types and validation schemas.
- Integrations that send and receive HTTP requests to outside services.
- A Next.js site with a Payload CMS panel: both run on Node.js as the runtime.
Not a fit when
- Heavy calculation, such as processing large files, that cannot be moved off the main loop.
- A team that knows only another backend language and has no reason to change.
- A simple static site that needs no server to run.
When the app is meant to calculate more than wait for data, I consider a backend language other than JavaScript.
Frequently asked questions
A backend that mostly waits for data?
Describe what the app should do with its data and where the data comes from. I will say whether Node.js is the right pick, or whether another language or a ready service is better.