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

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

DEV Community

Decoding Solana Account Data: Three Methods Compared MCP Just Landed on Your Phone: What Google AI Edge Gallery Actually Does I Made My Website "Alive" using Physics (Vanilla JS Experiment Part 2) 🚀 Stop Asking “Which Model?” and Start Fixing Your Team’s AI Supply Chain [Image Test C] How to Prompt AI Tools to Write Accurate SQL Queries (And Why Most Developers Get This Wrong) Stop Asking “Which Model?” and Start Fixing Your Team’s AI Supply Chain [Image Test B] Stop Asking “Which Model?” and Start Fixing Your Team’s AI Supply Chain [Image Test A] PayPal and Stripe Are Not the Answer for Global Digital Sales Signs your WordPress site needs a headless CMS rebuild Sanity CMS vs Contentful for Next.js projects: an honest comparison Sanity vs Strapi vs Payload CMS: an honest comparison for 2026 Sanity CMS website cost in 2026: what founders actually pay INP for React Apps: Profiling and Eliminating Long Tasks Why Core Web Vitals Matter (and How I Improve Them) Why AI Agents Love Boring Code I got tired of manual WordPress maintenance across 8 client sites - so I automated all of it My PR Merged Into a Graveyard: On the Rise of Antigravity and the Fall of Open Source Private AI on a Normal Android Phone: Building Krexel with Gemma 4 E2B The Best Result This Week Was a Failed Prediction — Phase-3a Doesn't Transfer Embedding 685 million texts in 32 minutes I Asked the Top 6 AI Chatbots to Sell Me on Themselves - Then Asked Each One Who Came Second Hello World JahSeeToo The First Malaysia's Hacker i watched google tear down the old internet from a hostel room in kolkata How I audit and prune unused Sanity document types to reclaim Studio performance What is MCP, and why it's the missing layer between AI and your CRM Stop adding print statements to debug your data pipeline — use watcher instead Hire a Sanity developer vs agency: five honest trade-offs Temporal vs Make for API-First Workflows The Antigravity 2.0 Forced Update: How to Fix the Broken Editor Loop 10 Ways To Reduce Your LLM API Costs mcp-probe v1.0.0: A CI readiness gate for MCP servers Building ValoVault: The Per-Agent Skin Loadouts Riot Never Shipped 45 MB of Claude Code Sessions You Don't See Most CMS Platforms Aren’t Built for Full Lifecycle Ownership Building a Resilient Checkout in NestJS: Retry, Idempotency, and a System That Tunes Itself Html learning journey I built an open-source alternative to ViciDial. Here's the stack, and the bugs that ate my nights. Zero-PC Architecture: Deploying Webhooks & AI Triage from a Mobile Footprint Why AI Coding Agents Fail Senior Engineers (And What I Built to Fix It) Stop Pasting URLs into Security Header Sites - Use This CLI 26 of 39 AI Companies Use SPF Softfail — Their Email Can Be Spoofed Mastering useRef in React: The Hook That Gives React Memory Without Re-Rendering One Brain, Many Hands: Building a Parallel Task Orchestrator for AI Agents Understanding useRef in React: Concepts, Use Cases, and Examples An AI That Can't Trade, a Human That Can't Say No SSH died. Spent 3 hours fixing the wrong thing. ## Rise of the Managed Agent: Why Antigravity 2.0 is Google I/O 2026’s Most Critical Developer Release From Concept to Production: A Technical Guide to Deploying Markus Multi-Agent Systems First Principles Why Browsers Outpaced Web Tooling (And How We Catch Up) Building a Safety-First RAG Triage Agent in Python Gemma 4 Isn’t Just Another AI Model — It’s A Shift In How We Build AI The Feature Store: Consistency and Latency Are Both Non-Negotiable What did gemma see? - Thinking in comments... I Built a Desktop Chat App for Running Local LLMs Offline Alert Fatigue Is a Design Choice: Building Views That Actually Help Building A Laravel Google Sheets Package That Imports, Exports, Caches, Formats, And Tests Cleanly DOM Accessibility Tree Extraction: A Reliable Method for LLMs on Dynamic Web Tables Building a Production Grade AWS Infrastructure Project (Part 1) Google just shifted the agent workflow from the cloud to the desktop I built a Claude skill that keeps your AI coding tools from contradicting each other — and I need beta testers Google I/O 2026 - Day 1 - Live from the Front Row The Effect of Frosted Glass (Glassmorphism) in Pure CSS in 2026 Gemini vs. ChatGPT for Coding: A Developer's Guide Solana's Account Types Are Just Database Rows With Different Flags Cryptographic Forensics for AI Coding Agent Sessions Testing NGB Platform Beyond a Small Demo Dataset with k6 and TypeScript Metabase 61: AI fun police, build questions and dashboards with MCP, and much more! How GBase 8a Rough Index Works: Block‑Level Pruning for 10x Faster Queries The Anti-Antigravity Bulkhead vs Rate limiting. The Age of Accountable Agents: Building Trust in Your AI Automation Securing Your AI Agents: Essential Practices for On-Device Automation I benchmarked OpenAI's new GPT-Realtime-Translate against four other live translation systems The Code Nobody Will Delete Building a desktop studio for interactive video stories like Late Shift - Devlog #1 Solving the Local AI Sandbox Issue: How TaigaAI Keeps Your Workstation Safe Why Enterprises Will Struggle With MCP — And What to Do About It Why I Finally Added a Blog to My Converter Tool When Your Coding Agent's String-Matcher Becomes a Billing Decision Building ThreatPulse IDS: An AI-Powered Intrusion Detection System I Built a Register-VM JavaScript Engine in Rust with opencode.ai — Beating QuickJS Per-User OAuth for AI Agents: Why It Matters and What to Look For You Got Your Whole Genome Sequenced. Now What? Zero to Full-Stack in 6 Months: The Izzy Way... PasteCheck v1.3 — what I improved after launching and getting real users DeepSeek V4 on Huawei's Ascend 950: A Real Stress Test for China's AI Chip Ecosystem How Strong Is "Strong"? Password Entropy in Plain English Precision Mechatronics: Mitigating Step-Pulse Resonance and Thermal Dissipation in Micro-Stepping Hardware Controllers A Fact A Day, an autonomous Podcast as my entry 4 Hermes Agent Challenge #100DaysOfSolana Day29: My Experience Generating Token On Solana Devnet Overcoming Challenges and Applying Best Practices in Migrating Large JavaScript Codebases to TypeScript Decostruire lo Streaming di FC2: Come Costruire un Downloader ad Alte Prestazioni con HLS e WebAssembly Top 10 Agentic AI Frameworks Compared: LangGraph vs CrewAI vs AutoGen vs... (Benchmarks Inside) How I Built a Hermes Agent for Lead Generation That Finds and Qualifies Better Prospects The Hybrid Method: when Claude.ai supervises Claude Code LLMs Are Probabilistic. Your Workflow Shouldn't Be. Deploying Tempo Distributed Tracing Backend on Ubuntu 24.04 Deploying Technitium DNS Server Platform on Ubuntu 24.04
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