2020-07-26
|~2 min read
|373 words
One of the actions that Gatsby provides is createRedirect
. Unfortunately, it does not work “out of the box” and actually requires a plugin.
This is a big departure from other Gatsby actions - which may explain why I couldn’t understand why it wasn’t working for me for a long time.
The instructions seemed straightforward:
The code for the redirect can be lifted straight from the documentation, but here’s an example where the current page is aware of the old route:
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node
const next = index === 0 ? null : posts[index - 1].node
const path = post.node.fields.slug
const oldPath = `oldish${path}`
createPage({
path: path,
component: blogPost,
context: {
slug: path,
previous,
next,
},
})
createRedirect({ fromPath: oldPath, toPath: path, isPermanent: true })
})
Configuring the plugin is potentially as simple as adding one line to the plugin’s list in gatsby-config.js
:
module.exports = {
plugins: [
//...
{ resolve: "gatsby-plugin-client-side-redirect" }, // keep-last
],
}
Here I’m using the client side redirect plugin which is deployment agnostic, however, I’ve also tested the Netlify redirect plugin, which offers some additional features that are intriguing (eg., setting, changing, and transforming headers).
Unfortunately all of my local testing told me that the “old path” couldn’t be found.
It turns out that middle step between configuration and profit is actually important!
Here’s the final version:
When testing a new feature, it’s certainly preferable to confirm it works before deploying — but I simply could not figure out how! So, I built a test site and deployed on Netlify (because it’s that simple), and was able to confirm the redirects work as expected!
Here’s one area where Netlify really shines - creating deployments of branches is really simple.
The demo site (using client-side redirection) is available here. To see an “oldish” post, prefix any post with /oldish
, e.g., /oldish/new-beginnings
. In terms of performance, it does seem like Netlify’s redirects are snappier, so if you’re already deploying with Netlify, I would recommend using that plugin.
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!