2026-08-20 14:26
Status:
//Personal notes
(get would be if you only want to send something out WITHOUT getting data first, but post would be if you wanted to send data back after getting something basically)
Node.js + Express — Backend Fundamentals
1. What Node Actually Is
Node is not a framework — it’s a JavaScript runtime. Before Node, JavaScript only ran inside a browser. Node takes the same V8 engine Chrome uses and lets JS run directly on a machine, with no browser involved — so it can open files, listen on network ports, and stay running indefinitely as a background process.
Key distinction: React code runs in the user’s browser — it exists only while that tab is open. A Node/Express backend runs on the server, continuously, independent of any browser tab. It’s alive whether or not anyone is currently looking at your site, and it can hold onto things (files, database connections, in-memory data) across many different requests from many different people.
Installed via nvm (Node Version Manager) — lets you install/switch Node versions per-project without conflicts.
nvm install --lts # install latest stable Node
nvm use --lts # switch to it
node -v # confirm version2. package.json and npm
npm (Node Package Manager) ships with Node. It does two things: installs third-party code, and tracks what your project depends on.
npm init -y — creates package.json, a manifest file for the project. -y skips the interactive Q&A and accepts defaults. This file doesn’t contain any of your actual code — it’s metadata: project name, version, and (most importantly) a dependencies list.
{
"name": "backend",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"express": "^4.19.2",
"better-sqlite3": "^11.1.2",
"bcryptjs": "^2.4.3"
}
}npm install <package> (or npm i) does three things:
- Downloads the package (and everything it depends on) into
node_modules/ - Adds it to
dependenciesinpackage.json - Records exact resolved versions in
package-lock.json
Why node_modules/ is gitignored: it’s fully reproducible. Anyone with your package.json runs npm install and gets the same folder back — committing it would just be dead weight in the repo, not a security issue (that’s .env’s job to worry about).
Running your app:
node server.js # run once, manually
npx nodemon server.js # auto-restarts server.js on every file save (dev convenience)3. What Express Adds on Top of Node
Node alone has a built-in http module capable of running a server, but it’s low-level — you’d manually parse URLs, methods, and headers yourself. Express is a library that sits on top of http and gives you a much higher-level way to define “when a request like this comes in, run this function.”
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Server running on port 3000');
});require('express')— pulls in the library fromnode_modules/express()— creates an Express application object;appis your entire server from here onapp.listen(3000, ...)— the line that actually makes the server start accepting connections. Everything else just configures behavior; this is what turns the configuration into a live process
“Always listening” only holds while the Node process is alive. Closing the terminal/SSH session kills a manually-run server. Getting from “works when I run it by hand” to “actually always on” is a separate deployment step (systemd service, or an always-restarting Docker container) — not something app.listen gives you by itself.
4. The Request/Response Cycle
This is the core mental model for everything that follows.
Browser (or curl)
│
│ sends: METHOD + path (+ optional JSON body)
▼
Express matches METHOD + path → exactly one handler function
│
▼
Handler function runs → does whatever it needs → sends a response
│
▼
Browser's fetch() (or curl) receives the response
Important precision: Express doesn’t run anything for a request that doesn’t match a defined method+path pair — those get an automatic 404 with no handler code executing at all. Nothing is “listening for everything” by default; every route is an explicit, exact match.
Defining routes
app.get('/', (req, res) => {
res.send('Portal backend is alive');
});
app.post('/api/login', (req, res) => {
// ...
});app.get(path, handler)— only fires forGETrequests to that exact pathapp.post(path, handler)— only fires forPOSTrequests to that exact path- Same path can have both a
GETand aPOSThandler — they’re independent, matched by method and path together
GET vs POST, the practical rule of thumb:
| Method | Meaning | Example |
|---|---|---|
GET | ”Give me data” — no body, safe to repeat, cacheable | Fetching a user list |
POST | ”Here’s data, act on it” | Logging in, registering, creating a record |
PUT / PATCH | ”Update this existing thing” | Editing a profile |
DELETE | ”Remove this thing” | Deleting an account |
The handler function signature: (req, res) => {...}
req— everything about the incoming request:req.body(JSON payload, once middleware parses it),req.params(URL segments like/users/:id),req.query(?key=valuein the URL)res— your tool for sending a response back. You call exactly one of these per request:
res.send('plain text or HTML');
res.json({ key: 'value' }); // sends JSON, sets Content-Type automatically
res.status(404).send('Not found'); // set a status code, chainable with send/json
res.status(201).json({ id: 5 }); // common pattern: status + json together5. Middleware
Middleware is a function that runs on every request, before any specific route handler, doing some kind of prep work and then passing control onward.
app.use(express.json());Contrast with app.get: app.get('/', ...) only fires for GET /. app.use(...) with no path fires for every request, every method, every path — it runs first, unconditionally.
express.json() specifically: looks at the incoming request body, and if the Content-Type header says JSON, parses the raw text into a real JavaScript object and attaches it as req.body. Without this line, req.body is undefined, no matter what the client actually sent — this is one of the most common “why isn’t my data showing up” bugs for people new to Express.
const express = require('express');
const app = express();
app.use(express.json()); // ← middleware: runs on every request first
app.post('/api/login', (req, res) => {
const { username, password } = req.body; // ← only populated because of the line above
// ...
});
app.listen(3000);Other common middleware you’ll encounter later:
app.use(express.static('public')); // serve static files from a folder
app.use(cors()); // allow cross-origin requests (separate npm package)You can also write your own middleware — any function with the signature (req, res, next) counts:
function logRequests(req, res, next) {
console.log(`${req.method} ${req.path}`);
next(); // ← must call this or the request hangs forever, never reaching the route handler
}
app.use(logRequests);next() is the hand-off — it says “I’m done, move on to whatever’s next in the chain” (either another middleware, or the matching route handler).
6. JSON — What It Actually Is
JSON (JavaScript Object Notation) is a text format for representing structured data. That’s the whole thing — it’s not a JavaScript-only concept, just a syntax that happens to look like JS object/array literals, used as the standard way systems in any language pass structured data to each other over HTTP.
{
"username": "natan",
"isAdmin": false,
"roles": ["viewer", "editor"],
"profile": {
"email": "[email protected]"
}
}Rules that trip people up coming from JS object literals:
- Keys must be double-quoted strings —
{ username: "x" }is valid JS, invalid JSON - No trailing commas
- No comments
- No functions, no
undefined— only strings, numbers, booleans,null, objects, and arrays
The JSON round-trip, and where each side of your stack touches it:
React object → JSON.stringify() → JSON text → (travels over HTTP) → JSON text → express.json() middleware → JS object (req.body)
// React side — sending
fetch('http://localhost:3000/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }) // JS object → JSON text
});
// Express side — receiving
app.post('/api/login', (req, res) => {
console.log(req.body); // already a JS object again — express.json() did the reverse conversion
});JSON.stringify(obj)— JS object → JSON text (string)JSON.parse(text)— JSON text (string) → JS objectexpress.json()middleware is doingJSON.parsefor you automatically on every incoming request body
Why the Content-Type: application/json header matters: it’s how the receiving side knows the body is JSON in the first place, rather than plain text, form data, or something else. Leave it off and express.json() won’t parse the body at all — req.body stays undefined, same symptom as forgetting the middleware entirely.
7. curl — Talking to Your Own Backend Without a Browser
curl is a command-line tool for making HTTP requests. It’s the standard way to test a backend before wiring up any frontend — isolates backend correctness from frontend correctness, so if something’s broken you know immediately which side it’s on.
GET request (default — no flags needed)
curl http://localhost:3000/POST request with a JSON body
curl -X POST http://localhost:3000/api/login \
-H "Content-Type: application/json" \
-d '{"username":"testuser","password":"testpassword123"}'curl -X POST http://localhost:3000/api/login \ -H "Content-Type: application/json" \ -d @login.jsonLogin — this sets the session cookie and writes it to cookies.txt
curl -c cookies.txt -X POST http://localhost:3000/api/login \ -H "Content-Type: application/json" \ -d @test-requests/login.json \ -w "\nStatus: %{http_code}\n"
Change password — reuse the SAME cookie file, now sent back to the server
curl -b cookies.txt -X POST http://localhost:3000/api/change-pwd \ -H "Content-Type: application/json" \ -d @test-requests/change-pwd.json \ -w "\nStatus: %{http_code}\n"Flag breakdown:
| Flag | Meaning |
|---|---|
-X POST | Sets the HTTP method (GET is the default if omitted) |
-H "Content-Type: application/json" | Adds a header — this one is what makes express.json() actually parse the body |
-d '{...}' | The request body (data) being sent — the single quotes protect the JSON’s double quotes from your shell |
Seeing status codes and headers, not just the body
curl -i http://localhost:3000/api/login # -i = include response headers in output
curl -v http://localhost:3000/api/login # -v = verbose, shows the full request/response exchangeCommon gotcha
Forgetting -H "Content-Type: application/json" is the #1 reason a POST route’s req.body comes back undefined during curl testing even when the JSON middleware is correctly in place — curl sends the body as plain text by default without that header, so Express doesn’t know to parse it as JSON.
8. SQLite via better-sqlite3
Chosen over a raw JSON file specifically because: real SQL, UNIQUE constraints solve duplicate-checking for free (instead of manually scanning an array yourself), and it’s a single file — no separate database server or container needed, which fits a single-VM homelab setup better than Postgres/MySQL would for a small user table.
Note the “Sync” in the name is deliberate — unlike most Node database libraries, better-sqlite3 runs queries synchronously (no await needed), which keeps the code simpler for small-scale use.
const Database = require('better-sqlite3');
const db = new Database('portal.db'); // creates the file if it doesn't exist
// Create table (safe to leave permanently — IF NOT EXISTS won't wipe existing data)
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL,
password_hash TEXT,
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
// Insert — parameterized query (never string-concatenate values into SQL)
const insert = db.prepare(
'INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)'
);
insert.run('natan', '[email protected]', hashedPassword);
// Fetch one row
const getUser = db.prepare('SELECT * FROM users WHERE username = ?');
const user = getUser.get('natan'); // .get() → single row (or undefined)
// Fetch many rows
const getAll = db.prepare('SELECT * FROM users WHERE status = ?');
const pending = getAll.all('pending'); // .all() → array of rows? placeholders are non-negotiable. String-concatenating user input directly into SQL (`SELECT * FROM users WHERE username = '${username}'`) is exactly how SQL injection happens — a malicious username value could contain SQL that alters the query itself. Parameterized queries keep values and query structure completely separate no matter what’s inside the value.
9. Password Hashing with bcryptjs
Never store a plaintext password, ever, under any circumstance. The hash is a one-way transformation — you can check whether a given plaintext matches a stored hash, but you can never reverse a hash back into the original password.
const bcrypt = require('bcryptjs');
// Hashing (at registration / password-set time)
const hash = bcrypt.hashSync(plainTextPassword, 10);
// 10 = cost factor (number of hashing rounds). Higher = slower to compute = harder to brute-force.
// The salt is generated and embedded into the resulting hash string automatically — no
// separate salt storage or management needed.
// Comparing (at login time)
const isMatch = bcrypt.compareSync(plainTextPassword, storedHash);
// compareSync extracts the salt from storedHash internally and re-hashes the input
// to check — you never manually handle the salt on either side.Why plaintext-in-transit is fine but plaintext-at-rest is not: a password travels from React to Express as plain text inside the request body — that’s normal and correct because the entire trip happens inside HTTPS encryption. “Plaintext in the request body” (before it hits the wire) is not the same thing as “plaintext on the wire” (which HTTPS prevents). The rule that actually matters: never persist (save to disk/database) a plaintext password — only the bcrypt hash ever gets written to storage.
10. Putting It Together — A Real Route
const express = require('express');
const bcrypt = require('bcryptjs');
const Database = require('better-sqlite3');
const app = express();
const db = new Database('portal.db');
app.use(express.json());
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
if (!user || !bcrypt.compareSync(password, user.password_hash)) {
return res.status(401).json({ error: 'Invalid username or password' });
}
if (user.status !== 'approved') {
return res.status(403).json({ error: 'Invalid username or password' });
}
res.json({ success: true, username: user.username });
});
app.listen(3000, () => console.log('Server running on port 3000'));Deliberate security detail: both failure paths (wrong credentials, and correct credentials but not-yet-approved) return the identical generic message and don’t reveal which thing was wrong. This prevents username enumeration — an attacker probing the login endpoint can’t distinguish “that username doesn’t exist,” “that password is wrong,” or “that account isn’t approved yet” from the response alone.
11. HTTP Status Codes Worth Knowing
| Code | Meaning | Typical use |
|---|---|---|
200 | OK | Successful GET, or generic success |
201 | Created | Successful POST that created a new resource |
400 | Bad Request | Malformed input, failed validation |
401 | Unauthorized | Missing/invalid credentials |
403 | Forbidden | Authenticated, but not allowed to do this |
404 | Not Found | No matching route, or resource doesn’t exist |
409 | Conflict | e.g. username already taken (UNIQUE constraint violation) |
500 | Internal Server Error | Something broke on the server side, not the client’s fault |
res.status(code) sets this explicitly — if you never call it, Express defaults to 200 on res.send/res.json.
12. Environment Variables and .env
Secrets (API keys, etc.) never get hardcoded into your source files or committed to git — they live in a .env file, gitignored, and get loaded at runtime.
npm install dotenvrequire('dotenv').config(); // loads .env into process.env — call this once, at the top of server.js
const resendKey = process.env.RESEND_API_KEY;.env file (never committed):
RESEND_API_KEY=re_actual_secret_key_here
.env.example (committed — documents which variables exist, without real values):
RESEND_API_KEY=
13. Glossary
- Runtime — the environment that actually executes your code; Node is a JS runtime outside the browser.
- Server — a continuously-running process that listens for and responds to network requests.
- Endpoint / Route — a specific method+path combination (
POST /api/login) mapped to a handler function. - Handler — the
(req, res) => {...}function that runs when its route is matched. - Middleware — a function that runs on every (or matching) request before the route handler, typically doing prep work like parsing or logging.
req/res— the incoming request object and the outgoing response object, passed into every handler.- Body — the data payload sent with a request (mainly relevant for POST/PUT/PATCH).
- JSON — a text format for structured data, used as the standard way frontend and backend exchange information over HTTP.
- Serialization — converting a data structure into a transportable format (
JSON.stringify); the reverse is deserialization/parsing (JSON.parse). - Parameterized query — a SQL query using placeholders (
?) for values instead of string concatenation, preventing SQL injection. - Hashing — a one-way transformation of data (like a password) that can be verified but not reversed.
- Salt — random data mixed into a hash to ensure identical inputs don’t produce identical hashes; bcrypt manages this automatically.
- Environment variable — a configuration value (often secret) supplied outside the source code, typically via a
.envfile. - CGNAT / Tunnel (homelab-specific) — Carrier-Grade NAT means no public IP is assigned to your connection; a tunnel (e.g. Cloudflare Tunnel) creates an outbound-only connection so external traffic can still reach a locally-hosted server without opening router ports.
References
Express req / res / app — Method Reference
res — Sending Data Back Out
Every route handler must end in exactly one of these. Calling more than one res method on the same request throws an error (“headers already sent”).
| Method | Example | What It Does |
|---|---|---|
res.send() | res.send('Portal backend is alive') | Sends a raw response — string, buffer, or object. Express guesses the Content-Type for you. Fine for plain text/simple responses. |
res.json() | res.json({ success: true }) | Sends a JS object, serialized to a JSON string, with Content-Type: application/json set automatically. Use this for basically all API responses in this project. |
res.status() | res.status(401).json({ error: '...' }) | Sets the HTTP status code. Chainable — doesn’t send anything by itself, needs a .send()/.json()/.end() after it. |
res.end() | res.end() | Ends the response with no body at all. Used for things like a bare 404 with nothing to say. |
res.redirect() | res.redirect('/login') | Sends a redirect response (302 by default), telling the browser to go fetch a different URL. Relevant for your eventual “redirect to webtop on login” step. |
res.sendFile() | res.sendFile('/path/to/file.html') | Sends the contents of a file directly as the response. Not used in a pure JSON API like yours, but common for serving static pages. |
res.set() / res.header() | res.set('X-Custom-Header', 'value') | Manually sets a response header. Rarely needed — most common headers are set automatically by res.json()/res.send(). |
res.cookie() | res.cookie('session', token) | Sets a cookie on the response. Relevant once you implement login sessions. |
req — Reading Data That Came In
| Property/Method | Example | What It Is |
|---|---|---|
req.body | const { username, password } = req.body | The parsed request body. undefined unless the matching body-parsing middleware (express.json(), etc.) ran first. |
req.params | req.params.id for route /users/:id | Values captured directly from the URL path itself, via :name segments in the route definition. |
req.query | req.query.sort for /users?sort=asc | The query string, parsed into an object. Always strings, even for things that look like numbers. |
req.method | req.method → 'POST' | The HTTP method of the incoming request. |
req.path | req.path → '/api/login' | The path portion of the URL, no query string. |
req.headers | req.headers['content-type'] | All incoming headers, as an object. Lowercase keys. |
req.headers.authorization | — | Common spot for auth tokens (Bearer <token>), relevant once sessions/JWTs come in. |
req.ip | req.ip | The requesting client’s IP address. Useful for logging or basic rate-limiting logic. |
req.get() | req.get('Content-Type') | Shortcut for reading a specific header, case-insensitive. |
app — Setting Up the Server Itself
| Method | Example | What It Does |
|---|---|---|
app.get() | app.get('/', handler) | Registers a handler for GET requests to a specific path. |
app.post() | app.post('/api/login', handler) | Registers a handler for POST requests to a specific path. |
app.put() | app.put('/api/users/:id', handler) | Registers a handler for PUT (full update) requests. Not used yet in this project. |
app.delete() | app.delete('/api/users/:id', handler) | Registers a handler for DELETE requests. Not used yet in this project. |
app.use() | app.use(express.json()) | Registers middleware — runs on every matching request, before route handlers. Path-less = runs on everything. |
app.listen() | app.listen(3000, callback) | Starts the server listening on a given port. The line that actually makes the server “on.” |
app.set() | app.set('trust proxy', true) | Sets an app-wide config value. trust proxy specifically matters once you’re behind Cloudflare Tunnel and want req.ip to reflect the real client IP, not the tunnel’s. |
app.route() | app.route('/users').get(...).post(...) | Chains multiple methods for the same path in one declaration, instead of separate app.get/app.post calls. |
express.Router() | const router = express.Router() | Creates a mini sub-app of routes, meant to be exported from its own file and mounted onto the main app — the structure mentioned for splitting routes into routes/auth.js etc. |