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

推荐订阅源

G
GRAHAM CLULEY
T
Tenable Blog
Know Your Adversary
Know Your Adversary
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
S
Security Affairs
NISL@THU
NISL@THU
O
OpenAI News
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News: Ask HN
Hacker News: Ask HN
Webroot Blog
Webroot Blog
Schneier on Security
Schneier on Security
S
SegmentFault 最新的问题
S
Schneier on Security
G
Google Developers Blog
V
V2EX
C
Check Point Blog
U
Unit 42
Google DeepMind News
Google DeepMind News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
T
The Exploit Database - CXSecurity.com
Recent Announcements
Recent Announcements
M
MIT News - Artificial intelligence
S
Secure Thoughts
博客园 - 司徒正美
Recorded Future
Recorded Future
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
K
Kaspersky official blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
博客园 - 聂微东
N
News and Events Feed by Topic
SecWiki News
SecWiki News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
Recent Commits to openclaw:main
Recent Commits to openclaw:main
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
The Hacker News
The Hacker News
The Last Watchdog
The Last Watchdog
Project Zero
Project Zero
W
WeLiveSecurity
博客园 - Franky

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 Updated: BFF Pattern 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
How to Build a REST API with Node.js and Express from Scratch
Abdullah She · 2026-05-19 · via DEV Community

How to Build a REST API with Node.js and Express from Scratch

Create a production‑ready RESTful API step‑by‑step using Node.js, Express, and modern best practices

Before We Start: What You'll Walk Away With

By the end of this guide you’ll be running a complete CRUD REST API on your laptop, just like having a personal kitchen where you can order, update, delete, or view any dish you’ve prepared.

We’ll walk you through the whole project layout, so you’ll know exactly why each folder exists—think of it as packing a suitcase where every item has its own compartment, making the trip smoother.

You’ll also get comfortable with middleware, routing, error handling, and a dash of security, similar to using Google Maps: the router tells requests where to go, middleware adds the traffic rules, and error handling warns you when you hit a dead end.

  • Spin up a Node.js server with Express and see it respond to HTTP verbs.

  • Organize code into controllers, routes, and models so future changes feel like swapping out a single ingredient.

  • Add basic protections—like checking a password before entering a club—to keep unwanted traffic out.

  • Node.js: the engine that runs your JavaScript on the server.

  • Express: the lightweight framework that routes requests, like a maître d' directing guests to tables.

  • CRUD: Create, Read, Update, Delete – the four actions you’ll master.

When you clone the repo, you’ll see a ready‑made structure you can tweak: change a route, add a field, or point it at a cloud database without rebuilding from scratch.

In short, you’ll finish with a copy‑and‑paste‑ready API you can extend or deploy wherever you need it.

What a REST API Actually Is (No Jargon)

A REST API is simply a collection of URLs that accept HTTP verbs—GET, POST, PUT, DELETE—to let one program ask another for data or tell it to change something. Think of each URL as a door and the verb as the way you knock; the response is whatever the other side hands you back.

Picture a restaurant menu. The menu lists dishes (those are your resources). You, the diner, send a waiter a request: “I’d like the salad GET,” “Add a drink POST,” “Swap the fries for a side of veggies PUT,” or “Take the soup away DELETE.” The kitchen prepares the order and the waiter brings it back—that’s the API’s response.

Because the conversation follows a standard set of rules, any client that understands HTTP can “eat” at your API, whether it’s a web app, a mobile app, or a script you run from the command line. No need to share codebases or speak the same programming language; just follow the contract defined by the endpoints.

When you build REST API Node.js apps, you’re essentially drafting that menu, setting up the kitchen stations (routes), and training the waitstaff (middleware) so every request gets the right dish, quickly and predictably.

The 4 Mistakes Everyone Makes With REST APIs

Most of the pain you feel when a request blows up comes from a simple habit you’ve picked up early on.

Mixing business logic with routing code makes your server feel like a crowded kitchen where the chef also takes orders, washes dishes, and invoices the table. When the logic lives inside the route handler, any change forces you to rewrite the whole menu.

Ignoring proper error handling is like driving a car without a spare tire; a single flat punctures the whole journey. If a typo or missing DB field throws, the entire Node.js process exits and every client gets a 500.

Forgetting to validate input turns your API into an open‑door grocery store where anyone can walk in and dump anything on the shelves. Bad payloads slip into your database, open XSS doors, and corrupt analytics.

Not versioning the API is like packing a suitcase once and never checking the weight before a flight. The first time a client needs a new field, the whole bag shifts and the old travelers are forced to repack.

Spotting these four traps early saves you weeks of debugging when you build REST API Node.js projects.

Next, we’ll walk through the clean project layout that keeps each concern in its own drawer.

How to Build a REST API with Node.js and Express: Step‑by‑Step

Run npm init -y to create a package.json, then install the core tools:

  • express – the kitchen where your API is cooked

  • dotenv – the pantry that keeps secret ingredients safe

  • nodemon – the sous‑chef that restarts the server on every change

Lay out the project like a well‑organized toolbox:

  • /src

  • /src/routes

  • /src/controllers

  • /src/models

  • /src/middleware

In src/app.js, load environment variables, spin up an Express instance, and add app.use(express.json()) so the server can read JSON payloads.

Drop a quick health‑check route:

GET /api/health → returns { status: "OK" }

It’s like asking a waiter, “Is the kitchen open?”

Create src/routes/users.js and define the classic CRUD endpoints for a User resource.

Meet Alice. She can be created with POST /api/users, read with GET /api/users/:id, updated via PUT /api/users/:id, and removed with DELETE /api/users/:id.

Write matching functions in src/controllers/userController.js. Each controller receives req and res, performs the logic, then sends a JSON response.

Add a global error‑handling middleware at the bottom of app.js. It catches rejected promises and replies with a consistent error object.

Secure the API with a trio of middleware:

  • helmet – adds HTTP headers like a lock on the front door

  • cors – decides which origins can knock

  • express-rate-limit – prevents a rush of requests, similar to a line‑up manager

  • Validate input with joi before it reaches your controllers

Create a .env file containing PORT=3000 and any secret keys. dotenv.config() pulls these values into process.env.

Fire up the server with npm run start (script: nodemon src/app.js) and test each endpoint using Postman or curl. If everything responds, you’ve successfully built a REST API with Node.js.

A Real Example: Building a Todo List API for “Sam the Startup Founder”

Sam needs a tiny Todo API so he can demo his MVP to investors by Friday.

He follows the checklist from Section 4, turning a blank folder into a working service.

  • Project init: npm init -y, install express, dotenv, joi, express-rate-limit.

  • Folder layout: create src/ with routes/, controllers/, models/, and a root server.js.

  • Routes for /todos: one file todoRoutes.js that maps HTTP verbs to controller actions.

  • Controller logic: todoController.js handles create, read, update, delete, each returning JSON.

  • Validation schema: a Joi schema ensures every Todo has a title (string, required) and optional completed flag.

  • Rate limiting: a 100‑request‑per‑minute rule protects the public beta, just like a restaurant limits tables during rush hour.

Here’s what Sam’s files look like.

// src/routes/todoRoutes.js
const express = require('express');
const router = express.Router();
const { getTodos, createTodo, updateTodo, deleteTodo } = require('../controllers/todoController');

router.get('/', getTodos);
router.post('/', createTodo);
router.put('/:id', updateTodo);
router.delete('/:id', deleteTodo);

module.exports = router;

// src/controllers/todoController.js
const Joi = require('joi');
const todos = []; // in‑memory store

const schema = Joi.object({
title: Joi.string().required(),
completed: Joi.boolean().default(false)
});

exports.getTodos = (req, res) => res.json(todos);

exports.createTodo = (req, res) => {
const { error, value } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
const newTodo = { id: Date.now(), ...value };
todos.push(newTodo);
res.status(201).json(newTodo);
};

exports.updateTodo = (req, res) => {
const todo = todos.find(t => t.id == req.params.id);
if (!todo) return res.status(404).end();
const { error, value } = schema.validate(req.body);
if (error) return res.status(400).json({ error: error.details[0].message });
Object.assign(todo, value);
res.json(todo);
};

exports.deleteTodo = (req, res) => {
const index = todos.findIndex(t => t.id == req.params.id);
if (index === -1) return res.status(404).end();
todos.splice(index, 1);
res.status(204).end();
};

.env

PORT=3000
RATE_LIMIT_WINDOW=60 # seconds
RATE_LIMIT_MAX=100

  • Tip: Keep .env out of version control; it’s the key to build REST API Node.js projects that move between dev and prod.

Sam now has a functional Todo list API he can point his front‑end at and start showing off.

The Tools That Make This Easier

Think of your development setup like a well‑organized kitchen – you need the right tools at hand so you don’t waste time chopping onions when you could be cooking the main dish.

  • Visual Studio Code with the ESLint and Prettier extensions – the chef’s knife and cutting board. VS Code’s built‑in terminal lets you stir the pot without opening another window, while ESLint catches syntax mistakes before they spoil the broth and Prettier keeps the code tidy.

  • Postman (free tier) – the taste‑tester. Just as you’d sample a sauce before serving, Postman lets you fire requests at each endpoint, view responses, and tweak headers without leaving the editor.

  • npm and npx – the pantry and instant‑cook packets. npm stores all your dependencies, and npx runs one‑off commands (like creating a new Express project) without cluttering your global install.

  • Swagger UI Express – the restaurant menu that updates itself. Write an OpenAPI spec and Swagger UI Express serves an interactive page where anyone can explore and try your API, just like a digital menu that lets diners see ingredients.

  • GitHub Codespaces – the portable kitchen. Spin up a cloud‑based VS Code instance that already has Node, npm, and the extensions you need, so you can start cooking from any laptop, any network.

These five tools cover code editing, testing, dependency management, documentation, and environment setup, giving you a streamlined workflow to build REST API Node.js projects without the usual setup headaches.

Quick Reference: REST API with Node.js Cheat Sheet

Grab this list whenever you need to spin up a new API—think of it as a quick‑order menu for your backend.

  • Project init: Run npm init -y, then install the core stack with npm i express dotenv cors helmet morgan. It’s like ordering the basic ingredients before cooking.

  • Folder layout: Create /src with subfolders routes, controllers, and middleware. Treat each folder as a separate kitchen station.

Core files:

  • app.js – sets up Express, middleware, and routes.

  • server.js – calls app.listen and reads the port.

  • routes/*.js – defines endpoint paths.

  • controllers/*.js – holds the business logic.

CRUD pattern: Map resources to the classic set—

  • GET /resources – list all.

  • GET /resources/:id – fetch one.

  • POST /resources – create.

  • PUT /resources/:id – replace.

  • DELETE /resources/:id – remove.

Like ordering a meal: you can view the menu, pick a dish, change it, or send it back.

  • Validation: Plug a Joi schema into route middleware. For example, Alex the travel blogger sends a new post; the schema checks title length, content presence, and date format before the controller runs.

  • Error handling: Wrap async handlers, call next(err), and let a global error middleware format the response. It’s the “Google Maps reroute” when something goes off‑track.

  • Security: Add helmet for headers, cors for cross‑origin rules, a rate‑limit middleware, and keep secrets in .env. Think of it as locking the kitchen door and only handing keys to trusted staff.

  • Docs: Generate live API docs with swagger-jsdoc + swagger-ui-express. Users can explore endpoints the way a menu lets diners see every option.

Keep this cheat sheet bookmarked and you’ll build a REST API with Node.js in no time.

What to Do Next

Grab the starter repo, fire it up, and you’ll have a working API in seconds.

  • Clone & run – Click the GitHub link at the top of the article, git clone it locally, then npm install followed by npm run dev. Think of this like ordering a ready‑made pizza: the dough and sauce are already prepared, you just heat it up and start eating.

  • Add JWT auth – Install jsonwebtoken, create a middleware that checks the token, and wrap your Todo routes with it. It’s similar to giving a valet key that only lets you open the right doors.

  • Deploy to the cloud – Sign up for a free tier on Render or Railway, push your code, set the same environment variables you used locally, and flip the switch for automatic HTTPS. Deploying is like packing a suitcase: you’ve already chosen what to bring, now you just zip it up and head out.

  • Quick tip: Keep your .env file out of version control; services provide a secure place to store those values.

  • Tool suggestion: Use nodemon during development so the server restarts whenever you save a file.

  • Cheat sheet: npm run dev → start locally; npm run build → prepare for production; npm start → run the built app.

Now you have a solid base, a layer of security, and a live endpoint you can share.

💬 Got stuck or added a cool feature? Drop a comment below—let’s discuss!



About the Author

Abdullah Sheikh is the Founder & CEO at Exteed, where he leads a team of skilled developers specializing in Web2 and Web3 applications, Custom Smart Contracts, and Blockchain solutions.

With 6+ years of experience, Abdullah has built CRMs, Crypto Wallets, DeFi Exchanges, E-Commerce Stores, HIPAA Compliant EMR Systems, and AI-powered systems that drive business efficiency and innovation.

His expertise spans Blockchain, Crypto & Tokenomics, Artificial Intelligence, and Web Applications — delivering scalable, secure, and high-performance solutions tailored to each client's unique needs.

📧 info@abdullah-sheikh.com · 🔗 LinkedIn · 🌐 abdullah-sheikh.com