We're going to learn how to create an API route that can read 0 or many dynamic segments from a URL.
Instructor: [0:00] Let's create a folder called optional-catch-all. Now, let's create a file that starts with angle bracket then it is followed by three dots then its dynamic parameter is going to be called slugs. We close the angle brackets, and this is a JavaScript file.
[0:24] The next thing that we have to do is to create a function called handler(). This function will receive a request object and a response object. We're going to export that handler function as a default export.
[0:43] The last thing that we want to do is to grab the slugs from the request.query and we're going to return that as a JSON.
[0:56] Now, let's make a request to the /api/ optional-catch-all endpoint. We see that we get back at 200 and an empty object. This is because we didn't pass anything after the optional catch-all route.
[1:13] Let's call the same endpoint with A, B and C. We see that we get back the slugs and an array with A, B and C.
[1:24] To recap, in order to create an optional catch-all route, what we have to do is that we have to create a file that starts with our angle bracket, then it is followed by three dots. Then we name the dynamic segment, and we close with double angle bracket again. After doing that, we can grab the dynamic segment from the request.query object.
[1:47] Also, if we don't pass anything to the catch-all route, we get back an empty object. If we pass any number of URL params to the catch-all route, we get back those params back as an array of strings.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!