diff --git a/docs/Guides/Migration-Guide-V4.md b/docs/Guides/Migration-Guide-V4.md index 71c228d7f5..2eee6bffab 100644 --- a/docs/Guides/Migration-Guide-V4.md +++ b/docs/Guides/Migration-Guide-V4.md @@ -130,6 +130,27 @@ As a result, if you specify an `onRoute` hook in a plugin you should now either: }); ``` +### Optional URL parameters + +If you've already used any implicitly optional parameters, you'll get a 404 +error when trying to access the route. You will now need to declare the +optional parameters explicitly. + +For example, if you have the same route for listing and showing a post, +refactor this: +```js +fastify.get('/posts/:id', (request, reply) => { + const { id } = request.params; +}); +``` + +Into this: +```js +fastify.get('/posts/:id?', (request, reply) => { + const { id } = request.params; +}); +``` + ## Non-Breaking Changes ### Deprecation of variadic `.listen()` signature diff --git a/docs/Reference/Routes.md b/docs/Reference/Routes.md index b1283a5ba4..8d0ffb522b 100644 --- a/docs/Reference/Routes.md +++ b/docs/Reference/Routes.md @@ -290,6 +290,17 @@ fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', function (request, r In this case as parameter separator it is possible to use whatever character is not matched by the regular expression. +The last parameter can be made optional if you add a question mark ("?") to the +end of the parameters name. +```js +fastify.get('/example/posts/:id?', function (request, reply) { + const { id } = request.params; + // your code here +}) +``` +In this case you can request `/example/posts` as well as `/example/posts/1`. +The optional param will be undefined if not specified. + Having a route with multiple parameters may negatively affect performance, so prefer a single parameter approach whenever possible, especially on routes that are on the hot path of your application. If you are interested in how we handle