Client-only routes will exist on the client only and will not correspond to html
files in an app’s built assets.
You can do that in two steps:
Create a main entry point page manually. In our example we would like to have a few client side pages a /app/details
page and a /app/profile
page. Our entry point page should /app
.
Configure Gatsby to navigate to the client only routes.
In your gatsby-node.js
file
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// Only update the `/app` page.
if (page.path.match(/^\/app/)) {
// page.matchPath is a special key that's used for matching pages
// with corresponding routes only on the client.
page.matchPath = '/app/*'
// Update the page.
createPage(page)
}
}
Instructor: [0:00] Let's take a look at our profile and stats pages. If you click on profile, you can see here we need to do a login. This is a protected route. After login, you can see it's specific to the user. This in Gatsby world means that we need to create client-only routes or dynamic pages. To do that, let's go to our Gatsby project.
[0:27] First, we need to create the entry page. This will be app, as you can see here in the routes, it's saying app in the profile. We will have app.js. Here, we can define some more routes using the React way. Let's import React. For routes, we will use reach routers. Let's define the app.
[0:49] Before we forget, let's export it. First thing, let's wrap everything in our router. Inside of that, we need to define the components that we have -- one being profiled and the second is that.
[1:02] Let's go to our React app and look for the profile and the stats component. You can see we have them here. Let's copy this and paste it here. These can be moved to also a separate file, and then we can import them. For the sake of this exercise, we can inline them here.
[1:20] Inside of app, we need to define profile and give it a path of app/profile. We'll do the same for stats. Then here, we'll change profile to stats and the component to stats. Now, we need to go to the Gatsby-node and export an onCreatePage callback. Here, we will do exports. This will be an isLink() function. We will extract page and actions as arguments. Let's first extract createPage from actions.
[1:52] Here, we tell Gatsby, "If the pagePath matches anything that starts with app, we need to update some settings." If page.path.match, and then here we give it to regex. If it starts with /app, and you need to escape the slash will change the matchPath to app/ *.
[2:14] Here, we update the page again, so we need to call createPage and pass the new page. Let's hit save. Let's stop our server and then run it again. Here, let's switch to our Gatsby app. Let's refresh and then click on profile. You can see here we have the profile and stats. You can see here we have the stats app.