Gatsby dynamic route for user profile URL Code Answer

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.


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


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


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

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

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji