Routing
Routing is defined as the process of mapping URL paths to specific server-side logic.
Intent vs. Location
When a client makes a request to a server, two primary components determine how the server handles it: the HTTP Method and the URL Path.
🎯 The "What" (Intent)
HTTP Methods (GET, POST, PUT, DELETE) define the action or intent of a request. They tell the server what needs to be done.
📍 The "Where" (Location)
Routing defines the resource path. It tells the server exactly where to look or where to apply the intended action.
Static Routes
Static Routes are fixed URL paths that do not change. They are typically used to serve a specific collection of resources or a single, unchanging entity.
- Exact string matching.
- Always return the same type of data.
- Examples:
/api/booksor/about-us.
Dynamic Routes
Dynamic Routes contain variable parameters denoted by a colon (e.g., :id). This allows the server to extract specific real-time information directly from the requested URL path.
Instead of writing hundreds of static routes for every user (/users/1, /users/2), you write one dynamic route pattern (/users/:id). Express automatically parses the URL and places all dynamic variables inside the req.params object.
Query Parameters
Query parameters are key-value pairs added to the end of a URL (separated by ? and &). They are used primarily with GET requests to filter, sort, search, or paginate data without changing the core route.
Nested Routing
Nested Routing defines hierarchical relationships between resources. It naturally maps to how relational data is structured in your database (e.g., a User has many Posts).
Instead of fetching a post globally by its ID, nested routing ensures you are fetching a specific post belonging to a specific user. It reinforces ownership and context directly within the URL logic:
Route Versioning
As your API evolves, you will inevitably introduce breaking changes. Route Versioning helps manage these changes by including explicit version numbers directly in the URL (e.g., /api/v1/...). This allows you to safely deprecate older versions seamlessly while new clients adopt the updated endpoints without crashing existing apps.
Catch-All Routes
A Catch-All Route acts as an organized fallback mechanism. It cleanly captures requests for paths that do not exist (e.g., when a user makes a typo in the URL).
- Returns a friendly, structured JSON "Not Found" error rather than the default, unresponsive HTML page provided by the web framework.
- In Express, the asterisk (
*) acts as a universal wildcard, matching literally any route. app.all()catches all HTTP methods universally (GET, POST, PUT, DELETE, etc.).- Critical Requirement: Because routing evaluates sequentially from top to bottom, this must be the very last route declared in your codebase.