DEV Community

Cover image for Route Components: Query, Params, and Body
Over-k
Over-k

Posted on Edited on

Route Components: Query, Params, and Body

Introduction
The distinctions between query parameters, route parameters (params), and request body is crucial. Let's dive into each and unravel their unique roles in building robust APIs and some practical guidelines for each type to reinforce best practices:
(In the realm of Express.js)

1. Query Parameters:

Query parameters are key-value pairs appended to the URL, typically used for filtering or specifying actions.

GET /api/posts?tag=JavaScript
Enter fullscreen mode Exit fullscreen mode
const tag = req.query.tag;
Enter fullscreen mode Exit fullscreen mode

Avoid Sensitive Information

Do not include sensitive information like passwords in query parameters.
Query parameters are often visible in URLs and can be logged, exposing sensitive data. Instead, use them for non-sensitive information like filters or flags.

2. Route Parameters (Params):

Params are variables in the route path, extracting values dynamically. Useful for identifying a specific resource.

GET /api/users/:id
Enter fullscreen mode Exit fullscreen mode
const userId = req.params.id;
Enter fullscreen mode Exit fullscreen mode

Validate and Sanitize Inputs

Always validate and sanitize route parameters to prevent malicious input.
Route parameters come directly from the URL, making them susceptible to attacks. Ensure they meet expected criteria and sanitize them to prevent issues like SQL injection.

3.Request Body:

The request body carries data, often in JSON format, for operations like creating or updating resources.

POST /api/users with body { "name": "OverK", "age": 0 }
Enter fullscreen mode Exit fullscreen mode
const { name, age } = req.body;
Enter fullscreen mode Exit fullscreen mode

Use HTTPS for Sensitive Data

When sending sensitive information in the request body, ensure your API uses HTTPS for secure data transmission.

The request body is suitable for carrying sensitive data, but transmitting it over an unsecured connection could expose the information. HTTPS encrypts the data during transmission.

Understanding when and how to use query parameters, route parameters, and request body is fundamental for effective Express.js API development. Each serves a distinct purpose, contributing to the flexibility and functionality of your endpoints.

Top comments (0)