How to resolve trailing slash on refresh in GatsbyJS

Viewed 296

i'm facing trailing slash issue similar to this How to remove trailing slashes in gatsby project?. when I try to reload just for second it is loading url with trailing slash like website.com/page1/ and then it is going back to website.com/page1. its happening for the ones i created in gatsby-node.js . I have tried remove trailing slashes plugin but didn't get the result

I will be grateful for any help. Thank you.

Here is how my gatsby-node.js looks like

const path = require(`path`)
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  // query content for WordPress posts
  const {
    data: {
      allWpLandingPage: { nodes: allLandingPages },
      allWpPost: { nodes: allPosts },
    },
  } = await graphql(`
    query {
      allWpLandingPage {
        nodes {
          id,
          slug,
          landing_page{
            baseFolder
          }
        }
      }

      allWpPost {
        nodes {
          categories {
            nodes {
              slug
            }
          }
          blogPostInfo {
            adressForUrl
            img {
              mediaItemUrl
              altText
            }
          }
          author{
            node{
                name
            }
          }
          content
          id
          title
        }
      }
    }

  `)
  const postTemplate = path.resolve(`./src/pages/landing.js`);

  allLandingPages.forEach(post => {
    let title = post.landing_page.baseFolder.toLowerCase().replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(' ').join('-');
    post.uri = title + '/' + post.slug;

    createPage({
      // will be the url for the page
      //path: post.slug,
      path: '/' + post.uri ,
      // specify the component template of your choice
      component: slash(postTemplate),
      // In the ^template's GraphQL query, 'id' will be available
      // as a GraphQL variable to query for this post's data.
      context: {
        id: post.id,
      },
    })
  })

  let filteredPosts = allPosts.filter((item) => {
    for (let i = 0; i < item.categories.nodes.length; i++){
        if (item.categories.nodes[i].slug === "blog-posts"){
            return item;
        }
    }
  });

  const blogPostTemplate = path.resolve(`./src/pages/article-page.js`);

  filteredPosts.forEach(post => {
    createPage({
      path: 'blog/' + post.blogPostInfo.adressForUrl,
      component: slash(blogPostTemplate),
      context: {
        id: post.id,
      },
    })
  })

}
2 Answers

Have you tried removing the trailing slash in the slug creation?

createPage({
  path: '/' + post.uri.replace(/\/$/, ""),
  component: slash(postTemplate),
  context: {
    id: post.id,
  },
})

The replace(/\/$/, "") regular expression should do the trick

Related