Build a Production-Ready REST API with Node.js & Express
What We're Building
In this tutorial, we'll build a REST API with Node.js and Express that's actually ready for production — not just a "hello world" with a few routes.
By the end, you'll have:
- JWT authentication
- Input validation
- Rate limiting
- Error handling middleware
- A scalable folder structure
Setup
First, initialize your project:
bashmkdir my-api && cd my-api npm init -y npm install express jsonwebtoken bcryptjs express-rate-limit joi npm install -D nodemon typescript @types/node
Folder Structure
codesrc/ routes/ auth.ts users.ts middleware/ auth.ts validate.ts rateLimiter.ts controllers/ models/ utils/ app.ts server.ts
Pro tip: Keep your routes thin. All business logic goes in controllers.
Authentication Middleware
typescriptimport jwt from 'jsonwebtoken' import { Request, Response, NextFunction } from 'express'export const requireAuth = (req: Request, res: Response, next: NextFunction) => { const token = req.headers.authorization?.split(' ')[1] if (!token) return res.status(401).json({ error: 'No token provided' }) try { const decoded = jwt.verify(token, process.env.JWT_SECRET!) req.user = decoded next() } catch { res.status(401).json({ error: 'Invalid token' }) } }
Rate Limiting
typescriptimport rateLimit from 'express-rate-limit'export const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, message: { error: 'Too many requests, please try again later.' } })
That's the Foundation
From here you can add validation with Joi, connect to MongoDB or PostgreSQL, and deploy to Railway or Render in minutes. Full source code is linked below.
Leave a Comment
Get the newsletter
Dev tutorials, tool roundups, and career insights — delivered to your inbox. No spam, ever.
Free · No spam · Unsubscribe anytime