mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
79 words
1 minute
Building REST APIs with Node.js and Express
2026-07-03

Setting Up#

mkdir my-api && cd my-api
npm init -y
npm install express cors helmet morgan
npm install -D typescript @types/express @types/node tsx

Project Structure#

src/
├── routes/
│ ├── users.ts
│ └── posts.ts
├── middleware/
│ ├── auth.ts
│ └── errorHandler.ts
├── controllers/
│ └── userController.ts
├── types/
│ └── index.ts
└── app.ts

The 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();
// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
// Routes
app.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 all
userRouter.get('/:id', getUser); // Get one
userRouter.post('/', createUser); // Create
userRouter.put('/:id', updateUser); // Replace
userRouter.patch('/:id', patchUser); // Partial update
userRouter.delete('/:id', deleteUser); // Delete

Error 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/users gives 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/
Author
LeviFREE
Published at
2026-07-03
License
CC BY-NC-SA 4.0

Some information may be outdated

Table of Contents