Building a production-ready API requires more than just CRUD operations. This guide covers everything from project setup to deployment, including authentication, validation, error handling, and security best practices.
Project Structure
text
src/
├── controllers/ # Request handlers
├── middleware/ # Auth, validation, error handling
├── models/ # Database schemas
├── routes/ # API endpoints
├── services/ # Business logic
├── utils/ # Helper functions
├── validators/ # Request validation schemas
└── app.js # Express app setupAuthentication with JWT
javascript
const jwt = require('jsonwebtoken');
const generateToken = (userId) => {
return jwt.sign(
{ userId },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
};
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
next();
} catch (error) {
return res.status(401).json({ error: 'Invalid token' });
}
};100%Production ready
JWTAuthentication
ZodValidation
DockerDeployment