Create a Dynamic 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 read dynamic segments from a URL using dynamic routes.

Instructor: [0:01] Let's create a folder called dynamic.

[0:04] Now, let's create a file called openAngleBracketSlugWeCloseTheAngleBracket.js. Let's create a function called handler() that receives a request and a response. What we're going to do is, we are going to extract this log from the request.query. Let's return it as JSON. The last thing that we have to do is to export handler as a default export.

[0:42] Now, we're going to call the API/API/dynamic and let's add 1 here. As we can see, we are returning the 1 in the URL in the JSON response. Let's change 1 with 2 and we'll see that we are returning 2 as a slug. It's worth noting that if we try to visit dynamic/1/2, we get a 404 back, because that route doesn't exist.

[1:11] To recap, in order to create dynamic API routes, we have to create files that start with an angle bracket, then we can add the dynamic segment we want, and then we close the angle bracket. After that, we can get the dynamic segment from the request.query.

~ 2 years ago

Small mistake in the video, those are square brackets not angle brackets.

Alejandro Ñáñez
Alejandro Ñáñezinstructor
~ 2 years ago

thanks for your feedback, I’ll pay more attention next time! :)

Markdown supported.
Become a member to join the discussionEnroll Today