79 words
1 minute
Building REST APIs with Node.js and Express
Setting Up
mkdir my-api && cd my-apinpm init -ynpm install express cors helmet morgannpm install -D typescript @types/express @types/node tsxProject Structure
src/├── routes/│ ├── users.ts│ └── posts.ts├── middleware/│ ├── auth.ts│ └── errorHandler.ts├── controllers/│ └── userController.ts├── types/│ └── index.ts└── app.tsThe App Entry Point
import express from 'express';import cors from 'cors';import helmet from 'helmet';import morgan from 'morgan';import { userRouter } from './routes/users';import { errorHandler } from './middleware/errorHandler';
const app = express();
// Middlewareapp.use(helmet());app.use(cors());app.use(morgan('dev'));app.use(express.json());
// Routesapp.use('/api/users', userRouter);
// Error handling (must be last)app.use(errorHandler);
app.listen(3000, () => { console.log('Server running on port 3000');});RESTful Routes
import { Router } from 'express';
export const userRouter = Router();
userRouter.get('/', getUsers); // List alluserRouter.get('/:id', getUser); // Get oneuserRouter.post('/', createUser); // CreateuserRouter.put('/:id', updateUser); // ReplaceuserRouter.patch('/:id', patchUser); // Partial updateuserRouter.delete('/:id', deleteUser); // DeleteError Handling Middleware
import { Request, Response, NextFunction } from 'express';
class AppError extends Error { constructor(public statusCode: number, message: string) { super(message); }}
export const errorHandler = ( err: Error, req: Request, res: Response, next: NextFunction) => { if (err instanceof AppError) { return res.status(err.statusCode).json({ error: err.message, }); }
console.error(err); res.status(500).json({ error: 'Internal Server Error' });};Best Practices
- Use HTTP status codes correctly — 200 for success, 201 for created, 404 for not found
- Validate input — never trust client data, use a validation library like Zod
- Version your API —
/api/v1/usersgives you room to evolve - Rate limit — protect against abuse with
express-rate-limit - Use HTTPS — always, no exceptions
A well-designed REST API is predictable, consistent, and a joy to work with.
Share
If this article helped you, please share it with others!
Building REST APIs with Node.js and Express
https://blog.levifree.com/posts/building-rest-apis-with-express/ Some information may be outdated
Related Posts Smart
1
PostgreSQL: Essential Queries and Tips
Backend A curated collection of PostgreSQL queries, performance tips, and features that every backend developer should have in their toolkit.
2
Introduction to WebSockets: Real-Time Communication
Web Dev Learn how WebSockets enable real-time, bidirectional communication between client and server. Build a simple chat system from scratch.
3
Getting Started with Astro: The Modern Static Site Generator
Web Dev A beginner-friendly introduction to Astro, covering its island architecture, content collections, and why it's becoming a go-to choice for content-focused websites.
4
Docker for Beginners: Containerize Everything
DevOps Learn the fundamentals of Docker — from images and containers to Dockerfiles and docker-compose. A practical guide to containerizing your applications.
5
Deploying Apps with Vercel: Beyond the Basics
DevOps Go beyond basic deployments with Vercel — custom domains, environment variables, serverless functions, edge middleware, and monorepo setups.
Random Posts Random
1
Regex Cheat Sheet for Developers
Programming 2026-05-24
2
SSH Key Management: A Complete Guide
Security 2026-06-28
3
Introduction to WebSockets: Real-Time Communication
Web Dev 2026-05-28
4
Nginx Reverse Proxy: The Complete Setup Guide
DevOps 2026-06-13
5
GitHub Actions: Automate Your Workflow
DevOps 2026-06-22





