Securing APIs in Node.js & MySQL Projects: Best Practices & Code Examples
Best Practices for API Security in Node.js & MySQL
Securing APIs in Node.js & MySQL Projects
APIs are the backbone of modern web and mobile applications. When building APIs with Node.js and MySQL, security must be a top priority. This guide covers essential best practices and code examples to help you secure your APIs.
API Security Architecture
This diagram shows a layered approach to API security, including gateway, WAF, authentication, and database protection.
API Gateway & WAF
Use an API Gateway and Web Application Firewall (WAF) to centralize security, rate limiting, and request validation. This helps block malicious traffic before it reaches your Node.js app.
User to DB Flow
This diagram shows the secure flow from user to database, with authentication and authorization checks at each step.
1. Use HTTPS Everywhere
Always serve your API over HTTPS to encrypt data in transit. Use letsencrypt or a commercial SSL certificate.
2. Authentication & Authorization
- JWT (JSON Web Tokens): Use JWT for stateless authentication. Issue tokens on login and verify them on each request.
- Role-based Access Control (RBAC): Restrict access to sensitive endpoints based on user roles.
// Example: JWT middleware
const jwt = require('jsonwebtoken');
function authenticateToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
3. Prevent SQL Injection
Always use parameterized queries or ORM libraries (like Sequelize or Knex) to prevent SQL injection.
// Using mysql2 with placeholders
const [rows] = await db.execute('SELECT * FROM users WHERE id = ?', [userId]);
4. Input Validation & Sanitization
Validate and sanitize all incoming data using libraries like express-validator or joi.
5. Secure Sensitive Data
- Never store plain-text passwords. Always hash with
bcrypt. - Store secrets (DB credentials, JWT secrets) in environment variables, not in code.
6. Rate Limiting & Throttling
Protect your API from brute-force and DDoS attacks using rate limiting middleware like express-rate-limit.
7. Logging & Monitoring
Log all authentication attempts and errors. Use monitoring tools to detect suspicious activity.
8. Keep Dependencies Updated
Regularly update Node.js, MySQL, and all dependencies to patch known vulnerabilities.