Create a Catch All Next.js API route

Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

We're going to learn how to create an API route that can read at least one or more dynamic segments from a URL.

Instructor: [0:00] Let's start by creating a folder called catch-all/inside/pages/api. Let's create a file that its name starts with an angle bracket then it is followed by three dots. Then we're going to call it slugs. We close the angle bracket, and this is going to be a JavaScript file.

[0:22] The next thing that we're going to do is to create a function that is called handler(). It will receive a request, a response, and we are going to export it as the default export for this file. Let's grab those slugs from the request.query.

[0:48] Let's return a JSON to the client with these slugs that we just grabbed from the query. Let's try out this endpoint. Let's make an API request to api/catch-all/1. We'll see that we get back an array.

[1:07] The next thing that we're going to do is that we're going to add another parameter to a URL. For instance, let's start 2 here and as we can see, we get back slugs with and inside an array. It is worth noting that if we don't pass any URL param to the catch-all route, we're going to get back a 404.

[1:30] To recap, to create a catch-all route, we need to create a file that it starts with an angle bracket, and it is followed by three dots. Then we add the dynamic parameter name. We close the angle bracket, and this should be a JavaScript file. Then we can grab that dynamic parameter from the request.query, and that dynamic parameter will contain all the URL segments as an array of strings.

egghead
egghead
~ an hour ago

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

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

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!

Markdown supported.
Become a member to join the discussionEnroll Today