# Code Reference — Node.js

_12 pages_

---
# Node.js (/docs/node)



# Node.js [#nodejs]

Express, Fastify, HTTP servers.

Browse the sidebar for every cheat sheet in this section.

## Sections [#sections]

*All notes are listed in the sidebar.*


---

# Environment & Config (/docs/node/env-config)



# Environment & Config [#environment--config]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Configure Node apps with environment variables, optionally loaded from `.env` files via `dotenv` or platform secrets. Validate required keys at startup.

## 🔧 Core concepts [#-core-concepts]

| Source          | Use                                    |
| --------------- | -------------------------------------- |
| `process.env`   | Primary config bag                     |
| `.env` + dotenv | Local development                      |
| Host secrets    | Production (Vercel, Docker, K8s, etc.) |
| `NODE_ENV`      | `development` / `production` / `test`  |

| Practice            | Why                               |
| ------------------- | --------------------------------- |
| Fail fast           | Crash if required vars missing    |
| No secrets in repo  | Use `.env.example` templates only |
| Typed config module | Single parse point                |

## 💡 Examples [#-examples]

**Fail-fast config:**

```js
function required(name) {
  const v = process.env[name];
  if (!v) throw new Error(`Missing env: ${name}`);
  return v;
}

export const config = {
  port: Number(process.env.PORT || 9000),
  databaseUrl: required("DATABASE_URL"),
};
```

**dotenv (dev):**

```js
import "dotenv/config";
```

**`.env.example`:**

```shellscript
PORT=9000
DATABASE_URL=postgres://user:pass@localhost:5432/app
```

## ⚠️ Pitfalls [#️-pitfalls]

* `process.env` values are strings — `PORT` needs `Number(...)`.
* Loading `.env` in production can accidentally override platform secrets if misordered.
* Never log raw env objects — they often contain credentials.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/node/getting-started)
* [error\_handling.md](/docs/node/error-handling)
* [packaging.md](/docs/node/packaging)
* [Next.js/env.md](/docs/node/../next.js/env)


---

# Error Handling (/docs/node/error-handling)



# Error Handling [#error-handling]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Robust Node services distinguish operational errors (expected failures) from programmer bugs, return safe HTTP responses, and log details server-side.

## 🔧 Core concepts [#-core-concepts]

| Layer           | Approach                                                 |
| --------------- | -------------------------------------------------------- |
| Sync throw      | Caught by try/catch or framework                         |
| Async rejection | Must be handled or process warns/crashes                 |
| HTTP mapping    | Map errors → status codes                                |
| Process hooks   | `uncaughtException` / `unhandledRejection` (last resort) |

| Status    | Typical meaning           |
| --------- | ------------------------- |
| 400       | Bad input                 |
| 401 / 403 | Auth / forbidden          |
| 404       | Missing resource          |
| 409       | Conflict                  |
| 500       | Unexpected server failure |

## 💡 Examples [#-examples]

**Express async wrapper:**

```js
const wrap = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get("/user/:id", wrap(async (req, res) => {
  const user = await db.find(req.params.id);
  if (!user) {
    const err = new Error("Not found");
    err.status = 404;
    throw err;
  }
  res.json(user);
}));
```

**Central error middleware:**

```js
app.use((err, req, res, next) => {
  const status = err.status || 500;
  if (status >= 500) console.error(err);
  res.status(status).json({
    error: status >= 500 ? "Internal error" : err.message,
  });
});
```

**Fastify setErrorHandler:**

```js
fastify.setErrorHandler((err, req, reply) => {
  reply.status(err.statusCode || 500).send({ error: err.message });
});
```

## ⚠️ Pitfalls [#️-pitfalls]

* Leaking stack traces to clients exposes internals.
* Swallowing errors (`catch (e) \{\}`) hides outages.
* `uncaughtException` handlers that continue serving are unsafe — shut down and restart.

## 🔗 Related [#-related]

* [express\_middleware.md](/docs/node/express-middleware)
* [fastify\_basics.md](/docs/node/fastify-basics)
* [http\_server.md](/docs/node/http-server)
* [env\_config.md](/docs/node/env-config)


---

# Express Basics (/docs/node/express-basics)



# Express Basics [#express-basics]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Express is a minimal Node HTTP framework: an app, middleware stack, and route handlers. Widely used and flexible; you wire most pieces yourself.

## 🔧 Core concepts [#-core-concepts]

| API                | Role                                 |
| ------------------ | ------------------------------------ |
| `express()`        | Create app                           |
| `app.get/post/...` | Register route + method              |
| `app.use`          | Mount middleware or sub-app          |
| `req` / `res`      | Incoming request / outgoing response |
| `next`             | Pass control to next middleware      |

| `res` helper   | Effect                      |
| -------------- | --------------------------- |
| `res.send`     | Send string/Buffer/object   |
| `res.json`     | JSON + content-type         |
| `res.status`   | Set status code (chainable) |
| `res.redirect` | 3xx redirect                |

## 💡 Examples [#-examples]

**Minimal app:**

```js
import express from "express";

const app = express();
app.get("/", (req, res) => res.json({ ok: true }));
app.listen(9000);
```

**JSON body parsing:**

```js
app.use(express.json());

app.post("/users", (req, res) => {
  res.status(201).json(req.body);
});
```

**404 fallback:**

```js
app.use((req, res) => {
  res.status(404).json({ error: "Not found" });
});
```

## ⚠️ Pitfalls [#️-pitfalls]

* Forgetting `express.json()` leaves `req.body` undefined for JSON POSTs.
* Error-handling middleware must have 4 args `(err, req, res, next)` or Express skips it.
* Listening on a port already in use crashes at startup — check availability (9000+).

## 🔗 Related [#-related]

* [express\_middleware.md](/docs/node/express-middleware)
* [express\_routing.md](/docs/node/express-routing)
* [error\_handling.md](/docs/node/error-handling)
* [Comparisons/express\_vs\_fastify.md](/docs/node/../comparisons/express-vs-fastify)


---

# Express Middleware (/docs/node/express-middleware)



# Express Middleware [#express-middleware]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Middleware functions run in order on a request. Each can read/modify `req`/`res`, end the response, or call `next()`. Most Express power comes from composing middleware.

## 🔧 Core concepts [#-core-concepts]

| Signature               | Role                                |
| ----------------------- | ----------------------------------- |
| `(req, res, next)`      | Normal middleware                   |
| `(err, req, res, next)` | Error middleware (must be 4 params) |
| `app.use(fn)`           | All methods / paths (or mount path) |
| `app.use('/api', fn)`   | Only under `/api`                   |

| Built-in               | Purpose            |
| ---------------------- | ------------------ |
| `express.json()`       | Parse JSON bodies  |
| `express.urlencoded()` | Parse form bodies  |
| `express.static(dir)`  | Serve static files |
| `express.Router()`     | Modular mini-app   |

## 💡 Examples [#-examples]

**Logger middleware:**

```js
function logger(req, res, next) {
  console.log(req.method, req.url);
  next();
}
app.use(logger);
```

**Auth gate:**

```js
function requireAuth(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: "Unauthorized" });
  }
  next();
}
app.get("/private", requireAuth, (req, res) => res.send("ok"));
```

**Error middleware (last):**

```js
app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: err.message });
});
```

## ⚠️ Pitfalls [#️-pitfalls]

* Calling `next()` after `res.send` can throw "Cannot set headers after they are sent".
* Order matters: parsers before handlers; error middleware after routes.
* Async errors need `try/catch` + `next(err)` or a wrapper — Express 4 does not catch rejected promises by default (Express 5 improves this).

## 🔗 Related [#-related]

* [express\_basics.md](/docs/node/express-basics)
* [express\_routing.md](/docs/node/express-routing)
* [error\_handling.md](/docs/node/error-handling)
* [fastify\_plugins.md](/docs/node/fastify-plugins)


---

# Express Routing (/docs/node/express-routing)



# Express Routing [#express-routing]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Express matches HTTP method + path patterns to handlers. Use `Router` to split large apps into mountable modules.

## 🔧 Core concepts [#-core-concepts]

| Pattern              | Matches                             |
| -------------------- | ----------------------------------- |
| `/users`             | Exact path                          |
| `/users/:id`         | Param `req.params.id`               |
| `/files/*`           | Wildcard (version-dependent syntax) |
| `/` + `Router` mount | Prefixed paths                      |

| API                             | Role                       |
| ------------------------------- | -------------------------- |
| `app.METHOD(path, ...handlers)` | Method-specific            |
| `app.all`                       | Any method                 |
| `router.route(path)`            | Chain verbs for one path   |
| `req.params` / `req.query`      | Path params / query string |

## 💡 Examples [#-examples]

**Params and query:**

```js
app.get("/users/:id", (req, res) => {
  res.json({ id: req.params.id, q: req.query.q });
});
// GET /users/42?q=active
```

**Router module:**

```js
import { Router } from "express";

const users = Router();
users.get("/", (req, res) => res.json([]));
users.get("/:id", (req, res) => res.json({ id: req.params.id }));

app.use("/users", users);
```

**Route chaining:**

```js
router
  .route("/items/:id")
  .get((req, res) => res.send("get"))
  .put((req, res) => res.send("put"))
  .delete((req, res) => res.send("delete"));
```

## ⚠️ Pitfalls [#️-pitfalls]

* More specific routes must be registered before generic `/:id` catchers.
* `req.params` values are strings — coerce IDs explicitly.
* Trailing-slash behavior depends on settings; be consistent in clients and routes.

## 🔗 Related [#-related]

* [express\_basics.md](/docs/node/express-basics)
* [express\_middleware.md](/docs/node/express-middleware)
* [fastify\_basics.md](/docs/node/fastify-basics)
* [http\_server.md](/docs/node/http-server)


---

# Fastify Basics (/docs/node/fastify-basics)



# Fastify Basics [#fastify-basics]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Fastify is a high-performance Node web framework focused on schemas, plugins, and low overhead. Validation and serialization are first-class via JSON Schema.

## 🔧 Core concepts [#-core-concepts]

| API                      | Role                                  |
| ------------------------ | ------------------------------------- |
| `Fastify()`              | Create instance                       |
| `fastify.route` / `.get` | Register routes                       |
| `schema`                 | Validate request + serialize response |
| `reply`                  | Response object (`send`, `code`)      |
| `listen`                 | Bind host/port                        |

| Hook (examples) | When                |
| --------------- | ------------------- |
| `onRequest`     | Early request       |
| `preHandler`    | Before handler      |
| `onSend`        | Before payload sent |
| `onError`       | Error path          |

## 💡 Examples [#-examples]

**Minimal server:**

```js
import Fastify from "fastify";

const app = Fastify({ logger: true });
app.get("/", async () => ({ ok: true }));
await app.listen({ port: 9000, host: "0.0.0.0" });
```

**Schema validation:**

```js
app.post(
  "/users",
  {
    schema: {
      body: {
        type: "object",
        required: ["email"],
        properties: { email: { type: "string", format: "email" } },
      },
    },
  },
  async (req, reply) => {
    reply.code(201);
    return req.body;
  },
);
```

**Async handler errors:**

```js
app.get("/boom", async () => {
  throw Object.assign(new Error("nope"), { statusCode: 400 });
});
```

## ⚠️ Pitfalls [#️-pitfalls]

* Prefer `async` handlers or call `reply.send` — don't mix both carelessly.
* Validation errors return 400 by default; customize with `setErrorHandler`.
* Plugin encapsulation means decorations are not always global — register shared plugins at the right scope.

## 🔗 Related [#-related]

* [fastify\_plugins.md](/docs/node/fastify-plugins)
* [express\_basics.md](/docs/node/express-basics)
* [error\_handling.md](/docs/node/error-handling)
* [Comparisons/express\_vs\_fastify.md](/docs/node/../comparisons/express-vs-fastify)


---

# Fastify Plugins (/docs/node/fastify-plugins)



# Fastify Plugins [#fastify-plugins]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Fastify organizes features as plugins. Each plugin gets an encapsulated context (decorators, hooks, routes) unless you break encapsulation deliberately.

## 🔧 Core concepts [#-core-concepts]

| API                              | Role                          |
| -------------------------------- | ----------------------------- |
| `fastify.register(plugin, opts)` | Load plugin                   |
| `fp` (`fastify-plugin`)          | Share decorations with parent |
| `decorate` / `decorateRequest`   | Attach utilities              |
| `prefix` option                  | Mount routes under a path     |

| Pattern                  | Use when                                 |
| ------------------------ | ---------------------------------------- |
| Encapsulated plugin      | Isolate routes/hooks per feature         |
| `fastify-plugin` wrapper | Share DB client, auth, config            |
| Nested `register`        | Create contexts (e.g. `/v1` vs `/admin`) |

## 💡 Examples [#-examples]

**Feature plugin:**

```js
async function usersPlugin(fastify, opts) {
  fastify.get("/", async () => []);
}
await fastify.register(usersPlugin, { prefix: "/users" });
```

**Shared decoration with `fp`:**

```js
import fp from "fastify-plugin";

async function dbPlugin(fastify) {
  fastify.decorate("db", { query: async () => [] });
}
export default fp(dbPlugin);
```

**Nested context:**

```js
await fastify.register(async (scope) => {
  scope.addHook("preHandler", async (req) => {
    /* admin-only */
  });
  scope.get("/stats", async () => ({ ok: true }));
}, { prefix: "/admin" });
```

## ⚠️ Pitfalls [#️-pitfalls]

* Forgetting `fastify-plugin` means parent routes cannot see `fastify.db`.
* Circular plugin dependencies are hard to debug — keep a clear register order.
* Registering the same plugin twice can duplicate routes/hooks.

## 🔗 Related [#-related]

* [fastify\_basics.md](/docs/node/fastify-basics)
* [express\_middleware.md](/docs/node/express-middleware)
* [env\_config.md](/docs/node/env-config)
* [packaging.md](/docs/node/packaging)


---

# Getting Started with Node.js (/docs/node/getting-started)



# Getting Started with Node.js [#getting-started-with-nodejs]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Node.js is a JavaScript runtime built on V8 for building servers, CLIs, and tooling outside the browser. Packages are managed with npm, pnpm, or yarn.

## 🔧 Core concepts [#-core-concepts]

| Idea       | Meaning                                              |
| ---------- | ---------------------------------------------------- |
| Runtime    | Executes JS with Node APIs (`fs`, `http`, `process`) |
| Module     | CommonJS (`require`) or ESM (`import`) unit          |
| npm        | Default package manager + registry client            |
| Event loop | Schedules async I/O callbacks                        |
| LTS        | Long-term support release line (prefer for prod)     |

**Check install:**

```shellscript
node --version
npm --version
```

| Command               | Purpose                            |
| --------------------- | ---------------------------------- |
| `node app.js`         | Run a script                       |
| `npm init -y`         | Create `package.json`              |
| `npm install express` | Add dependency                     |
| `node --watch app.js` | Restart on file changes (Node 18+) |

## 💡 Examples [#-examples]

**Hello server:**

```js
import http from "node:http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello Node\n");
});

server.listen(9000, () => console.log("http://localhost:9000"));
```

**`package.json` type module:**

```json
{
  "name": "demo",
  "type": "module",
  "scripts": { "start": "node index.js" }
}
```

## ⚠️ Pitfalls [#️-pitfalls]

* Mixing CJS and ESM without clear `"type"` / extensions causes cryptic import errors.
* Global `npm install -g` tools can conflict across projects — prefer local + `npx`.
* Blocking the event loop with heavy sync CPU work starves all requests.

## 🔗 Related [#-related]

* [http\_server.md](/docs/node/http-server)
* [express\_basics.md](/docs/node/express-basics)
* [env\_config.md](/docs/node/env-config)
* [packaging.md](/docs/node/packaging)
* [glossary.md](/docs/node/glossary)


---

# Glossary (/docs/node/glossary)



# Glossary [#glossary]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Alphabetical glossary of Node.js runtime, modules, and server-framework terms.

## 🔧 Core concepts [#-core-concepts]

| Term             | Definition                                                   |
| ---------------- | ------------------------------------------------------------ |
| Buffer           | Fixed-size binary data type for bytes.                       |
| CJS              | CommonJS modules using `require` / `module.exports`.         |
| Event loop       | Core scheduler for timers, I/O, and microtasks.              |
| ESM              | ECMAScript modules using `import` / `export`.                |
| Express          | Minimal, unopinionated HTTP framework.                       |
| Fastify          | Schema-oriented, high-performance HTTP framework.            |
| libuv            | C library providing Node’s async I/O and threadpool.         |
| Middleware       | Function in a pipeline that can handle or forward a request. |
| npm              | Default package manager and registry client.                 |
| package.json     | Manifest for deps, scripts, and package metadata.            |
| Plugin (Fastify) | Encapsulated unit of routes, hooks, and decorations.         |
| semver           | Semantic versioning (`major.minor.patch`).                   |
| Stream           | Abstract interface for streaming data (readable/writable).   |
| Worker thread    | Separate V8 isolate for CPU-heavy work.                      |
| `node:` prefix   | Built-in module import specifier (`node:fs`).                |

## 💡 Examples [#-examples]

**Built-in import:**

```js
import fs from "node:fs/promises";
import { createServer } from "node:http";
```

**Detect ESM vs CJS mentally:**

```json
{ "type": "module" }
```

```js
// with "type": "module" → import works
// without → require is default unless .mjs
```

## ⚠️ Pitfalls [#️-pitfalls]

* “Node version” vs “framework version” — always note both when debugging.
* Global installs hide which binary your shell resolves — prefer local tooling.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/node/getting-started)
* [http\_server.md](/docs/node/http-server)
* [express\_basics.md](/docs/node/express-basics)
* [fastify\_basics.md](/docs/node/fastify-basics)
* [README.md](/docs/node)


---

# HTTP Server (node:http) (/docs/node/http-server)



# HTTP Server (node:http) [#http-server-nodehttp]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

`node:http` (and `node:https`) provide low-level servers and clients. Frameworks like Express/Fastify wrap these primitives.

## 🔧 Core concepts [#-core-concepts]

| API                       | Role                     |
| ------------------------- | ------------------------ |
| `http.createServer`       | Create server            |
| `IncomingMessage` (`req`) | Request stream + headers |
| `ServerResponse` (`res`)  | Writable response        |
| `server.listen`           | Bind port/host           |
| `http.request` / `fetch`  | Outbound HTTP            |

| Header tip      | Detail                                |
| --------------- | ------------------------------------- |
| Set before body | Call `writeHead` or `setHeader` early |
| `Content-Type`  | Required for correct client parsing   |
| Keep-alive      | Default in modern Node                |

## 💡 Examples [#-examples]

**Plain text server:**

```js
import http from "node:http";

http
  .createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ path: req.url }));
  })
  .listen(9000, "0.0.0.0");
```

**Read POST body:**

```js
async function readBody(req) {
  const chunks = [];
  for await (const c of req) chunks.push(c);
  return Buffer.concat(chunks).toString("utf8");
}
```

**Global fetch (Node 18+):**

```js
const res = await fetch("https://example.com");
const text = await res.text();
```

## ⚠️ Pitfalls [#️-pitfalls]

* Forgetting to `end()` the response leaves the client hanging.
* Unbounded body reads enable memory DoS — enforce size limits.
* `req.url` includes query string; parse with `URL` + host header carefully.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/node/getting-started)
* [express\_basics.md](/docs/node/express-basics)
* [fastify\_basics.md](/docs/node/fastify-basics)
* [error\_handling.md](/docs/node/error-handling)


---

# Packaging (/docs/node/packaging)



# Packaging [#packaging]

*Node.js · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Node projects are defined by `package.json`: dependencies, scripts, entry points, and module format. Publish libraries to npm or run apps via scripts.

## 🔧 Core concepts [#-core-concepts]

| Field              | Purpose                    |
| ------------------ | -------------------------- |
| `name` / `version` | Package identity (semver)  |
| `type`             | `"module"` for ESM default |
| `main` / `exports` | Entry points               |
| `dependencies`     | Runtime deps               |
| `devDependencies`  | Build/test-only deps       |
| `scripts`          | `npm run` commands         |
| `engines`          | Supported Node versions    |

| Command        | Effect                |
| -------------- | --------------------- |
| `npm install`  | Install from lockfile |
| `npm ci`       | Clean CI install      |
| `npm outdated` | Check updates         |
| `npm pack`     | Dry-run tarball       |

## 💡 Examples [#-examples]

**Minimal library `exports`:**

```json
{
  "name": "@acme/utils",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    ".": "./dist/index.js"
  },
  "files": ["dist"]
}
```

**Useful scripts:**

```json
{
  "scripts": {
    "dev": "node --watch src/index.js",
    "start": "node src/index.js",
    "test": "node --test"
  }
}
```

**Install exact tree in CI:**

```shellscript
npm ci
```

## ⚠️ Pitfalls [#️-pitfalls]

* Committing without a lockfile leads to non-reproducible installs.
* Publishing secrets or `.env` via bad `"files"` / missing `.npmignore` is catastrophic.
* Dual CJS/ESM packages need careful `exports` — test both consumers.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/node/getting-started)
* [env\_config.md](/docs/node/env-config)
* [glossary.md](/docs/node/glossary)
* [error\_handling.md](/docs/node/error-handling)

