⚠️ This lesson is retired and might contain outdated information.

Create Client Only Routes (Dynamic Pages)

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

Often you want to create a site with client-only portions, which allows you to gate them by authentication or load different content based on URL parameters.

You can create a client-only route page in two steps:

  1. 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.

  2. 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] Inside of our project, let's create a new page and call it app. Let's import React and router from reach router. Let's define a few components. We have profile, details, and default. We will use them in our main app.

[0:33] Here, let's create the app component. This will return a wrapper with a basePath app. Inside of there, let's use these three components. We wanted to render profile. If the path is /app/ profile, just duplicate this.

[1:01] Here, let's get details. Then here, the URL will be details and default if we go to just /app. Now, let's go to our gatsby-node.js.

[1:19] We need to export an onCreatePage function. This will give us the arguments page and actions. Let's get the createPage from actions. Now, we need to tell Gatsby to redirect all the requests that starts with /app to our app component, and it will take it from there. Here, with the if statement can say, "If page.path.match," and here, we can pass to regex.

[1:58] If anything starts with /app, we want to change the page.matchPath to be /app/*, and we want to create the page again with a new settings. Let's hit save, and let's run our server. Here, I missed the error.

[2:37] Let's go to our server. If we go to /app, you should see the default, which is this component, and /profile should show us the profiles component, which is this component here.

Venueplan
Venueplan
~ 4 years ago

My Ide throws error unless I export the App component. Sounds logical. But video and notes does not specify export on app.js