Route Wildcards
⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 14 min
Route wildcards allow pattern-based routing, where a single handler can match multiple URLs.
Overview
Pattern based routes are supported as well. For instance, the asterisk * is used as a wildcard, and will match any combination of characters.
This is useful when you want to create catch-all routes, handle legacy URL structures, or serve static assets dynamically.
Key Concepts
*Wildcard: The*character acts as a wildcard within route strings.- Regex Support: Under the hood, Nest uses the
path-to-regexppackage (used by Express), which means characters like?,+,*, and()have regex-like meanings. - Specificity: Wildcard routes should usually be placed at the bottom of your controller. Nest resolves routes top-to-bottom, so a generic wildcard at the top might accidentally intercept specific routes below it.
Code Examples
A Simple Wildcard Route
import { Controller, Get } from '@nestjs/common';
@Controller('assets')
export class AssetsController {
// This will match /assets/abcd, /assets/123, /assets/anything
@Get('ab*cd')
findAll() {
return 'This route uses a wildcard';
}
}
Catch-All Routes
Often used for returning a custom 404 page, or for single-page applications (SPAs) where you want to serve index.html for any unmatched route and let the frontend router handle it.
import { Controller, Get } from '@nestjs/common';
@Controller()
export class AppController {
@Get('specific-route')
getSpecific() {
return 'Specific data';
}
// CATCH ALL: Must be placed at the bottom!
// Matches literally any GET request that wasn't caught above.
@Get('*')
catchAll() {
return 'This acts as a fallback for any unmatched GET request';
}
}
Best Practices
- Route Ordering Matters: The order in which methods are defined in a controller matters. If you have
@Get(':id')above@Get('active'), the:idroute will catch the request for/active(treating “active” as the ID). Always put static routes first, parameter routes second, and wildcards last. - Avoid Overusing Wildcards: Wildcards can make routing unpredictable and difficult to debug. Prefer exact paths or explicit route parameters (
:id) over complex wildcard matching whenever possible.