Suppose that you want to make your site routing a little more flexible. For example, rather than just going straight to a 404 page if the path is not found, you might want to try and guess an appropriate (and valid!) path. This is where dynamic routing comes into play.
What’s the Problem?
Suppose that somebody tries to go to the path
/what-is-gatsby/ on the site. Now this is not a valid path, so will result in a 404 page. However, there are a number of similar valid paths:
Would it not be better to go to one of these rather than flinging out the 404 page? I certainly think so!
Types of Dynamic Routing
There are two types of dynamic routing in Gatsby:
We’ll be looking at the latter.
The […].js File
In a Gatsby site, a file named
[...].tsx) is used for dynamic routing. The square brackets
[...] indicate a catch-all route. This allows you to handle a variety of different URLs with a single file. This is useful for handling cases like:
- 404 pages;
- dynamic routes based on data; or
- any URL patterns that might not be known ahead of time.
Gatsby uses the
[...].js file as part of its file-based routing system, where the file and folder structure in the
src/pages directory directly translates into routes on the website. So, for example, you could have both a
src/pages/[...].js and a
We’ll create a file at
src/pages/[...].js that exports a function,
DynamicRoute(), that returns a component,
RedirectComponent. The component will accept an argument,
slug, which is extracted from the parameters passed to
The Redirect Component
src/components/redirect.js we define the component
RedirectComponent. This will do a few things:
- Construct a candidate path using the slug and the latest version.
- Check whether the candidate path is a valid path on the site.
- If it is valid then navigate to that path.
- If it is not valid then navigate to the 404 page.
The component will use
useEffect() to perform the actual navigation.
Do Try This at Home
Let’s give this a try. Go to the site.
- Try navigating to any one of the valid paths listed above. For example, try
- Now try navigating to a path without a version. For example, try
In the second case you will be redirected to the path
/1.2/what-is-gatsby/. A loading page might briefly appear while you are being redirected. Before implementing dynamic routing this path would have taken you to the 404 page.
We have taken a look at a simple application of dynamic routing. Using dynamic routes will make the routing on your site more flexible, providing alternative ways for you to send your users to the right content. You can make it as complicated and flexible as you want.