Dynamic Routes

There are many applications that require pages to be created dynamically. Next.js provides a robust feature set for this functionality.

Let’s talk about what dynamic routes are and how they work.

First, what if you had a news site that had different articles at different URLs?

For example:

  • somegreatnews.com/article/974232
  • somegreatnews.com/article/243423

Each article is a different subject matter, but the layout of the page would need to be the same. It might include a title, an image, some text for the body of the article, and perhaps some other common things that would work nicely on a news site.

Imagine that this site has thousands of articles. You wouldn’t want to create a new page for each one, right?

You would want to create a dynamic route that would grab the article id from the URL. This information is known as the route parameters and you can use that to retrieve the article data. With the data in hand, you can display it on the page.

Your homepage does a search for you and displays the results, but you have no way to save that search or share it with others. You can fix that by creating a dynamic route and accessing a route parameter to get your search terms.

Here are just a few URLs that would return search results for your users once you are done creating it:

  • somethingmadeup.com/search/cats
  • somethingmadeup.com/search/dogs
  • somethingmadeup.com/search/mincraft

This lesson will focus on creating the page and accessing the URL parameters. In the next lesson, you will grab the data from the Giphy API and display those results to your users.

How to make the dynamic route

Notice that in the route below, the word search is static. It will not change. The route parameter after the cats will change:

http://localhost:3000/search/cats

To get that static word search as part of your route, you will create a folder inside the pages folder and name it search.

Get hands-on with 1200+ tech skills courses.