Search code examples
gatsbyreach-router

Gatsby/Reach Router 404 but page renders


Building locally there is no issue, and the end user would not see any issue on a production build unless looking at the network tab. First page request 404's and then the page renders as expected.

Expected functionality

Render Dept Page component

/shop/
/shop/category-1/

Render PLP Page component

/shop/category-1/item-type/

Render PDP template, item name is key for content out of ContentStack, query params pull product data from separate product API

/shop/item-name?item=query-param&color=brown...

This all works except the initial 404 before the page renders.

Issue only present for pages behind the /shop/ route. All other site pages, routes, templates work without issue. Appreciate any suggestions.

In src/gatsby-node.js I've got

exports.onCreatePage = async ({ page, actions }) => {
  const { createPage } = actions;
    if (page.path === '/shop/') {
      page.matchPath = '/shop/*';
      createPage(page);
    }  
  };

exports.createPages = async ({ actions, graphql }) => {
const { createPage } = actions;
const pdpTemp = path.resolve("src/templates/pdp/index.js");

try {
    const result = await graphql(`
        {
            pdp: allContentstackPdp {
                edges {
                    node {
                        id
                        url
                    }
                }
            }
        }
    `);

    let node;

    // PDP Pages
    for (let i = 0; i < result.data.pdp.edges.length; i++) {
        node = result.data.pdp.edges[i].node;
        await createPage({
            path: node.url,
            component: pdpTemp,
            context: {
                pdpId: node.id
            }
        });
    }
}

catch (err) {
    throw new Error(err);
}
}

I've got a page with the following routing, src/pages/shop/index.js

render() {
return (
    <Router>
        {/* Department Pages */}
        <DEPT path='/shop/' />
        <DEPT path='/shop/category-1/' />
        <DEPT path='/shop/category-2/' />
        <DEPT path='/shop/category-3/' />
        {/* PLP Pages */}
        <PLP path='/shop/category-1/*' />
        <PLP path='/shop/category-2/*' />
        <PLP path='/shop/category-3/*' />
    </Router>
);
}

And a template that is also affected by this issue src/templates/pdp/index.js


Solution

  • The solution for us was to add 301 rewrites into AWS.