Gatsby dynamic route for user profile URL

I want to set up my router in pages/index.js and gatsby-node.js file to show user profiles via dynamic links. The user profile should have a URL like this: https://domain/user_name. When I visit this URL, it should show a UserPublicProfile component, now its showing 404 page with a not existing page. Also, I have an /app/ page which is then routing to other underlying application components. https://domain/app/ should be not routed as a profile URL, every other URLs after https://domain/ are just profile URLs.

I’m able to make it work by creating an additional page user-profile and then use URLs like https://domain/user-profile/user_name. But I need to have the URL in the form mentioned above.

gatsby-node.js

exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
if (page.path.match(/^/app/)) {
  page.matchPath = "/app/*"
  createPage(page)
}
else if (page.path.match(/^/(?!app).*/)) {
  page.matchPath = "/:id"
  createPage(page)
}
else if (page.path.match(/^/user-profile/)) {
  page.matchPath = "/user-profile/:id"
  createPage(page)
}}

pages/index.js:

import { Router } from "@reach/router";
<Router basepath="/">
        <PrivateRoute path="/user-profile" component={UserPublicProfile} />
        <PrivateRoute path="/" component={UserPublicProfile} />
      </Router>

Answer

I found a solution by using createPages function in gatsby-node.js.

https://www.gatsbyjs.com/docs/creating-and-modifying-pages/

    exports.createPages = async ({ actions: { createPage } }) => {
  // get all users to crete them a profile page
  axios
    .get(process.env.API_DOMAIN + "/getAllUsersPublicProfiles")
    .then(result => {
      var users = result.data.data;
      users.forEach((user) => {
        createPage({
          path: `/${user.link_tag}/`,
          component: require.resolve(
            "./src/components/userPublicProfile/userPublicProfile.js"
          ),
          context: { user: user },
        });
      });
    })
    .catch((e) => {
      console.log("Failed to load users data: " + e);
    });
};

Leave a Reply

Your email address will not be published. Required fields are marked *