Skip to content

How to Fix Circular Redirects in Gatsby

Gatsby/

Gatsby doesn’t tell you whether to use or omit trailing slashes. The choice to place a forward slash at the end of a URL is up to you.

Nonetheless, Gatsby’s default behavior implies that you should use them. This is further backed up by services such as Netlify where Pretty URLs are enabled by default. Jon Sullivan has written an excellent blog post about this topic — Trailing Slashes and Gatsby. You should read the post if you are interested to learn more.

But, how does this relate to redirect issues? Omitting the trailing slash can actually create loops in redirects.

Fixing Circular Redirects

If you are having circular redirects, you are most likely missing a / at the end of your page path.

Although you can omit them, you will have to do some extra work, which I won’t talk about in this post.

Instead, why not just do it the intended way? Go over the following list and see if you have forgotten to place a trailing slash somewhere.

  1. Make sure you add a trailing slash to all internal links.

    Whenever you use the Link component, add a trailing slash in the to prop. Don’t forget to use a trailing slash whenever you use navigate function as well.

  2. When you create pages by hand in gatsby-node.js, ensure that you pass paths with a trailing slash to createPage() function. You can also use gatsby-plugin-force-trailing-slashes plugin to do the job for you.

  3. If you have SEO set up for social media, make sure that canonical URLs in meta tags include a trailing slash.

    If a canonical URL lacks a trailing slash, crawlers get stuck in a loop. They open a page, find and fetch the canonical URL, which redirects to the same page but with a trailing slash. In this page they see the canonical URL without a trailing slash and repeat the same cycle.

  4. Make sure your siteUrl in gatsby-config.js matches your primary domain and not a secondary/alias domain.

    If you redirect your www.yourdomain.com to yourdomain.com, omit www in siteUrl. Otherwise, you create the same cycle as above, in this list’s item 3.

  5. If you have a sitemap, ensure all URLs contain a trailing slash.

    Doing so prevents search engines from indexing links which are redirects to the actual content. You want to have your real content displayed in search results and not redirect URLs.

To check if your page paths include a trailing slash, open http://localhost:8000/___graphql while running gatsby develop in a terminal. Then, run the following query.

{
  allSitePage {
    nodes {
      path
    }
  }
}

You should see all of your site’s pages and their corresponding paths.