惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

L
LangChain Blog
Security Latest
Security Latest
P
Proofpoint News Feed
GbyAI
GbyAI
PCI Perspectives
PCI Perspectives
博客园 - Franky
N
Netflix TechBlog - Medium
博客园_首页
WordPress大学
WordPress大学
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Vercel News
Vercel News
T
Threatpost
The Hacker News
The Hacker News
H
Help Net Security
S
Securelist
Recent Announcements
Recent Announcements
腾讯CDC
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta
C
Cisco Blogs
V
V2EX
C
Check Point Blog
S
Schneier on Security
Cyberwarzone
Cyberwarzone
C
Cybersecurity and Infrastructure Security Agency CISA
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Jina AI
Jina AI
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
A
Arctic Wolf
AWS News Blog
AWS News Blog
Latest news
Latest news
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
The GitHub Blog
The GitHub Blog
小众软件
小众软件
B
Blog
aimingoo的专栏
aimingoo的专栏
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything BFF模式详解:构建前后端协同的中间层 I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What I Learned Building My First Express Server
Chinwuba · 2026-05-24 · via DEV Community

I'm primarily a frontend developer. React, Vite, Tailwind etc. that's my world. The backend has always been that thing I knew existed but rarely touched. Today I finally sat down and built my first Express server from scratch, and I want to document everything that actually clicked, including the things that didn't at first.

This isn't exactly a clean tutorial. It's a honest account of what I learned, what troubled me, and what I'd tell myself if I was starting over.

Setting up from zero

First things first:

```in your terminal run
npm init -y
npm install express




Then I created `server.js` and wrote the minimum possible server:


const express = require('express');

const app = express();

app.get('/', (req, res) => {
  res.send('Hello world');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});


```javascript

Run it with `node server.js`, open `http://localhost:3000` in the browser — "Hello world". That's a working HTTP server in about 10 lines.

Let me break down what each part is actually doing.

---

**Breaking down the code**

### `const express = require('express')`

This pulls the Express library from `node_modules` into the current file. `require` is CommonJS — the default module system in Node. You store it in a variable called `express`.

### `const app = express()`

You call `express()` like a function because it is one. It returns an application object — this `app` is your server's control panel. Everything attaches to it.

### The route


app.get('/', (req, res) => {
  res.send('Hello world');
});

Enter fullscreen mode Exit fullscreen mode

This registers a route. Let's read it out loud:

"When someone makes a GET request to /, run this function."

req is the request object — everything the client sent you. Their URL, query params, headers, body.

res is the response object — your tools for sending something back.

app.listen(3000, () => { ... })

This starts the server on port 3000. The callback runs once the server is ready — that's why you log there and not outside it.


The req/res naming thing

I assumed req and res were special keywords that Express required. They're not. They're just parameter names.

Express calls your callback with the request object first and the response object second, always. The names are completely up to you:

// All of these work identically
app.get('/', (req, res) => { res.send('ok') });
app.get('/', (request, response) => { response.send('ok') });
app.get('/', (banana, mango) => { mango.send('ok') });

Enter fullscreen mode Exit fullscreen mode

That last one is valid JavaScript. mango holds the response object and .send() works fine on it.

The community standardized on req and res so everyone reading your code immediately knows which is which. Stick with the convention, but knowing it's just a convention makes the whole thing less mysterious.


Reading data from the URL

There are two ways a client can send data in a GET request.

URL parameters

app.get('/user/:id', (req, res) => {
const id = req.params.id;
res.json({ userId: id });
});

The colon before id tells Express that this segment of the URL is a variable. So /user/jeffrey, /user/42, and /user/anything all hit this route. Whatever's in that slot gets stored in req.params.id.

You visit it like: http://localhost:3000/user/jeffrey

For multiple params, it's a slash between them, not a comma:

app.get('/add/:a/:b', (req, res) => {
// correct
});

app.get('/add/:a,:b', (req, res) => {
// wrong — this will not match the way you expect
});

I made the comma mistake. It cost me time.

Query parameters

app.get('/add', (req, res) => {
const a = Number(req.query.a);
const b = Number(req.query.b);
res.json({ sum: a + b });
});

You visit it like: http://localhost:3000/add?a=10&b=5

When to use which:

URL params are for identifying a specific resource — /user/42, /product/air-max. Query params are better for operations, filters, and optional values — /search?q=express, /add?a=10&b=5. For a math operation, query params are the natural fit.

Splitting logic into modules

Instead of writing all my functions inside the server file, I created a separate math.js:

// math.js
function add(a, b) {
return a + b;
}

function mult(a, b) {
return a * b;
}

module.exports = { add, mult };


Then imported it in the server:

Enter fullscreen mode Exit fullscreen mode


js
// server.js
const { add, mult } = require('./math');


This keeps the server file clean. Routes handle HTTP, modules handle logic. Good habit to build early.

---

** CommonJS vs ESModules**

Node has two module systems and I spent time going back and forth between them today.

**CommonJS:**

Enter fullscreen mode Exit fullscreen mode


js
const express = require('express');
module.exports = { add };


**ESModules:**

Enter fullscreen mode Exit fullscreen mode


js
import express from 'express';
export function add(a, b) { return a + b; }


The key differences:

- To use ESM in Node, you need `"type": "module"` in your `package.json`, otherwise Node treats `.js` files as CJS by default
- ESM requires file extensions when importing local files: `./math.js` not `./math`
- You cannot mix them freely. `require` in an ESM file breaks. `import` in a CJS file breaks.

**My recommendation if you're just starting:** stick with CommonJS. No config needed, works out of the box, and the vast majority of Express tutorials and packages are written in it. Switch to ESM when you have a concrete reason to.

---

## Handling POST requests

GET requests carry data in the URL. POST requests carry data in the **body** — like submitting a login form or hitting an API with JSON. You don't want a password showing up in someone's browser history.

Enter fullscreen mode Exit fullscreen mode


js
app.post('/login', (req, res) => {
const { username, password } = req.body;
res.json({ message: Welcome ${username} });
});


But there's a catch. To read `req.body`, you need this line **before** your routes:

Enter fullscreen mode Exit fullscreen mode


js
app.use(express.json());


`app.use()` applies middleware to every incoming request. `express.json()` reads the raw request body and parses it as JSON so you can access it via `req.body`.

I removed this line to see what would happen. Got this:

Enter fullscreen mode Exit fullscreen mode


plaintext
TypeError: Cannot destructure property 'username' of 'req.body' as it is undefined.


Without it, `req.body` is just `undefined`. The middleware is not optional — and it must come before your routes, not after.

To test POST requests, you can't use the browser URL bar. Use **Thunder Client** (VS Code extension) or Postman. Send a POST to `http://localhost:3000/login` with this JSON body:

Enter fullscreen mode Exit fullscreen mode


json
{
"username": "jeffrey",
"password": "velto123"
}


Response:

Enter fullscreen mode Exit fullscreen mode


json
{
"message": "Welcome jeffrey"
}

Small things that made me question my sanity

1. The app.listen callback

// Wrong — logs before the server is ready
app.listen(3000, console.log("Server running on port 3000"));

// Right — logs once the server is actually up
app.listen(3000, () => console.log("Server running on port 3000"));

Enter fullscreen mode Exit fullscreen mode

Without the arrow function, console.log executes immediately when the file loads, not when the server is ready. It's a subtle difference but it matters.

2. res.send() vs res.json()

res.send() is for plain text. res.json() is for objects and structured data. When you're building an API, you almost always want res.json().

3. Not restarting the server

Every time I made a change and wondered why nothing was different — the old server was still running. Fix this once:

node --watch server.js

Enter fullscreen mode Exit fullscreen mode

Built into Node 18+. No install needed. Your server restarts automatically on every file change.


Where I ended up

By the end of the session I had a working Express server with:

  • GET routes reading from URL params and query params
  • A separate math module with add and mult functions
  • A POST route reading from req.body
  • A solid mental model of how the whole thing fits together

If you're a frontend developer who's been avoiding Express the same way I was — it's genuinely not that far from home. The concepts map to things you already know. A route is just an event listener. Middleware is just a function that runs before your handler. req and res are just objects.

Start with a GET route. Break something. That's how it sticks.


I'm Chinwuba Jeffrey — frontend developer and CEO of Velto, a premium web design agency focused on the African market. I'm documenting my journey going full-stack. Follow along if you're on a similar path.