0
0
Expressframework~5 mins

Validating route params and query in Express

Choose your learning style9 modes available
Introduction

We check route parameters and query data to make sure they are correct before using them. This helps avoid errors and keeps the app safe.

When you want to make sure a user ID in the URL is a number.
When you need to confirm a search query is not empty.
When you want to check that a date parameter is in the right format.
When you want to prevent invalid or harmful data from reaching your app.
When you want to give clear error messages if input is wrong.
Syntax
Express
app.get('/path/:param', (req, res) => {
  const param = req.params.param;
  const queryValue = req.query.key;

  // Validate param and queryValue here

  if (/* validation fails */) {
    return res.status(400).send('Invalid input');
  }

  res.send('Valid input');
});

Route params come from req.params and query strings come from req.query.

Validation is usually done inside the route handler before using the data.

Examples
This checks if the id param is only digits.
Express
app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  if (!/^[0-9]+$/.test(id)) {
    return res.status(400).send('User ID must be a number');
  }
  res.send(`User ID is ${id}`);
});
This ensures the query term is not empty or missing.
Express
app.get('/search', (req, res) => {
  const term = req.query.term;
  if (!term || term.trim() === '') {
    return res.status(400).send('Search term is required');
  }
  res.send(`Searching for ${term}`);
});
This validates the date param matches the format YYYY-MM-DD.
Express
app.get('/event/:date', (req, res) => {
  const date = req.params.date;
  if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
    return res.status(400).send('Date must be YYYY-MM-DD');
  }
  res.send(`Event date is ${date}`);
});
Sample Program

This Express app has a route that checks if the product ID is a number and if the optional color query is one of the allowed colors. It sends an error if validation fails.

Express
import express from 'express';
const app = express();
const port = 3000;

app.get('/product/:productId', (req, res) => {
  const productId = req.params.productId;
  const color = req.query.color;

  // Validate productId is a number
  if (!/^[0-9]+$/.test(productId)) {
    return res.status(400).send('Product ID must be a number');
  }

  // Validate color is one of allowed values
  const allowedColors = ['red', 'blue', 'green'];
  if (color && !allowedColors.includes(color.toLowerCase())) {
    return res.status(400).send('Color must be red, blue, or green');
  }

  res.send(`Product ID: ${productId}, Color: ${color || 'default'}`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

Always validate both route params and query strings to avoid unexpected errors.

Use regular expressions or simple checks to validate formats and allowed values.

Send clear error messages with status 400 when input is invalid.

Summary

Validate route params from req.params and query strings from req.query.

Use simple checks or regex to confirm data is correct before using it.

Return a 400 error with a helpful message if validation fails.