Common mistakes to avoid while working with Express.js

Manthan Ankolekar - Dec 11 '23 - - Dev Community

Here are code snippets illustrating some common mistakes in Express.js along with their solutions:

1. Improper Error Handling:

Mistake:

app.get('/users', (req, res) => {
  // Logic to fetch users
  // If an error occurs:
  res.status(500).send('Internal Server Error');
});
Enter fullscreen mode Exit fullscreen mode

Solution:

app.get('/users', (req, res, next) => {
  // Logic to fetch users
  // If an error occurs:
  next(new Error('Unable to fetch users'));
});

// Error handling middleware
app.use((err, req, res, next) => {
  res.status(500).send({ error: err.message });
});
Enter fullscreen mode Exit fullscreen mode

2. Neglecting Security Measures:

Mistake:

// Handling a POST request without data validation
app.post('/login', (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  // Perform login without validating input
});
Enter fullscreen mode Exit fullscreen mode

Solution:

const { body, validationResult } = require('express-validator');

// Data validation middleware
app.post('/login', [
  body('username').isLength({ min: 5 }),
  body('password').isLength({ min: 8 }),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // Perform login after validating input
});
Enter fullscreen mode Exit fullscreen mode

3. Using Synchronous Operations:

Mistake:

app.get('/data', (req, res) => {
  const result = fetchData(); // Synchronous operation
  res.json(result);
});
Enter fullscreen mode Exit fullscreen mode

Solution:

app.get('/data', async (req, res) => {
  try {
    const result = await fetchData(); // Asynchronous operation
    res.json(result);
  } catch (error) {
    res.status(500).send('Error fetching data');
  }
});
Enter fullscreen mode Exit fullscreen mode

These examples demonstrate how to handle errors, implement data validation, and use asynchronous operations properly within Express.js to avoid common mistakes and ensure better code quality and security.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .