Skip to content

Blog

Securing APIs in Node.js & MySQL Projects: Best Practices & Code Examples

Best Practices for API Security in Node.js & MySQL

  • 3 min read
  • Updated

Securing APIs in Node.js & MySQL Projects

API Security LayersClientBrowser/AppTLSHTTPS1.3🔒RateLimiterDDoSProtection🛡️AuthJWTVerifyRBAC🔑InputValidationSanitizeJoi/Zod✅SQLParamPreparedStatements🗃️MySQLDatabaseDefense in Depth: Each layer prevents a class of attacksNo single layer is sufficient — security requires all layers working togetherLayer 1Layer 2Layer 3Layer 4Layer 5Encryptsall trafficBlocks bruteforce attacksVerifiesidentityPreventsXSS / injectPreventsSQL injection
API Security Diagram

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

API Security Architecture

This diagram shows a layered approach to API security, including gateway, WAF, authentication, and database protection.

API Gateway & WAF

API Gateway and 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

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

OWASP Top Threats & DefensesSQL InjectionMalicious queriesParameterized QueriesPrepared Statements & ORMBroken AuthWeak credentialsJWT + MFA + bcryptToken rotation & hashingXSSScript injectionInput SanitizationCSP headers & escapingSSRFInternal accessURL AllowlistNetwork segmentationMisconfigurationDefault settingsSecurity HardeningHelmet.js & auditEvery threat has a defense — implement all layers for complete protectionBased on OWASP Top 10 Web Application Security Risks

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.

Further Reading

Related reading. For an explainable edge Web Application Firewall on TenthMatrix WSL Proxy, see the WAF blog, the technical article, or wslproxy.org.