Skip to content

Instantly share code, notes, and snippets.

@johno
Created January 3, 2019 04:05
Show Gist options
  • Save johno/db2887f341cc3a3b1b2167661858aab6 to your computer and use it in GitHub Desktop.
Save johno/db2887f341cc3a3b1b2167661858aab6 to your computer and use it in GitHub Desktop.
Programmatic redirects in Gatsby

Programmatic redirects in Gatsby

In the frontmatter of your post you can specify legacy redirects.

---
title: foo
date: 2012-11-10
path: bar
redirects:
  - /posts/2012/11/10/foo
  - /other/thing
---

# ...

Then when creating pages you can look for redirects in frontmatter and programmatically create them.

if (node.frontmatter.redirects) {
  node.frontmatter.redirects.forEach(fromPath => {
    createRedirect({
      fromPath,
      toPath: path,
      redirectInBrowser: true,
      isPermanent: true
    })
  })
}

You can then add gatsby-plugin-meta-redirect and redirects will happen automagically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment