React
1800

Securing Your Node.js Application

A

Administrator

December 1, 2025

3 min read

Security Fundamentals

Security should be a top priority when building Node.js applications. Here are essential practices to follow.

Environment Variables

Never hardcode sensitive data:

// Bad
const apiKey = 'sk-1234567890abcdef';

// Good
require('dotenv').config();
const apiKey = process.env.API_KEY;

Input Validation

const validator = require('validator');

app.post('/user', (req, res) => {
  const { email, username } = req.body;
  
  if (!validator.isEmail(email)) {
    return res.status(400).json({ error: 'Invalid email' });
  }
  
  if (!validator.isAlphanumeric(username)) {
    return res.status(400).json({ error: 'Invalid username' });
  }
  
  // Process valid input
});

SQL Injection Prevention

// Bad - vulnerable to SQL injection
const query = `SELECT * FROM users WHERE id = ${req.params.id}`;

// Good - using parameterized queries
const query = 'SELECT * FROM users WHERE id = ?';
db.execute(query, [req.params.id]);

XSS Protection

const helmet = require('helmet');
const xss = require('xss-clean');

app.use(helmet());
app.use(xss());

Rate Limiting

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many requests from this IP'
});

app.use('/api/', limiter);

HTTPS and CORS

const cors = require('cors');

app.use(cors({
  origin: process.env.ALLOWED_ORIGINS?.split(','),
  credentials: true
}));

Security Checklist

  • ✓ Use HTTPS in production
  • ✓ Validate all user inputs
  • ✓ Use parameterized queries
  • ✓ Implement rate limiting
  • ✓ Keep dependencies updated
  • ✓ Use security headers (helmet)
  • ✓ Hash passwords (bcrypt)
  • ✓ Implement CSRF protection

Comments (0)

Please login to comment

No comments yet. Be the first to comment!

A

About Administrator

Default admin user

Related Articles