Something always goes wrong when you change hosting providers. No matter how many times you've been through this before. ๐
For me it was redirects. A vital feature of any site migration.
CodeWithSwiz is a weekly live show. Like a podcast with video and fun hacking. Focused on experiments and open source. Join live most Tuesday mornings
Last year I migrated my 13+ year old Wordpress blog to Gatsby. The migration is ongoing, several things remain wonky. You can read about exporting 1500 wordpress articles to markdown, here, and first steps on the journey here. From September 2019 ๐ฑ
Why thousands of redirects??
Redirects translate between Wordpress URLs and the new, cleaner, Gatsby URLs.
They come in 2 types:
- Article redirects in frontmatter
- Page redirects in
_redirects
Frontmatter redirects tell Gatsby to translate any old URLs to their new shape. Cool URLs don't change and my SEO tool says swizec.com gets 26,000 backlinks these days. ๐
Page redirects are for housekeeping.
/serverless-handbook
links to https://serverlesshandbook.dev
, /reactd3js
goes to https://reactfordataviz.com
, old images on /wp-content/
redirect to their new homes in /static/
(thousands of images), and a few others.
The incident
All this worked fine until one day I had the bright idea: "Eh now that Gatsby Cloud offers hosting, why do I keep paying for Netlify, it just slows down deploys"
I pressed the red button.
And it worked!
Gatsby Cloud is a great host and Gatsby is a self-contained system. Everything went great!
Switched DNS settings, turned off Netlify, nobody noticed.
Until a few weeks later โฆ wait something's weird. That's a lot of broken links and images. ๐คจ
Going from Netlify to Gatsby Cloud
You can go from Netlify to Gatsby Cloud quickly in theory. I was already using Gatsby Cloud for builds and deploying to Netlify.
Gatsby uses plugins to adapt itself for different hosts. Redirects and HTTP headers mostly.
On Netlify you use gatsby-plugin-netlify
. For Gatsby Cloud you'll change that to gatsby-plugin-gatsby-cloud
. Their config is about the same.
Change the DNS setting on your domain and that's it.
But you gotta tell Gatsby about all your redirects so the host plugin knows! That's what creates the final config.
Article redirects with markdown frontmatter
I wanted to keep article-specific redirects simple. Add configuration to each article instead of a global config file.
---
title: "My cool article"
description: "You should read this for sure"
categories: "epic, amazing"
redirect_from: /
---
Article frontmatter configures the title, description, categories, and a redirect_from. That's the old URL. Yes they're weird.
You make that work by hooking into Gatsby's page creation lifecycle in gatsby-node.js
exports.createPages = async ({ graphql, actions }) => {
const result = await graphql(`
{
allMdx(filter: { frontmatter: { redirect_from: { ne: null } } }) {
edges {
node {
fields {
slug
}
frontmatter {
redirect_from
}
}
}
}
}
`)
if (result.errors) {
console.log(result.errors)
throw result.errors
}
const allPosts = result.data.allMdx.edges
// For all posts with redirect_from frontmatter,
// extract all values and push to redirects array
allPosts.forEach((post) => {
const from = post.node.frontmatter.redirect_from
const to = post.node.fields.slug
from.forEach((from) => {
actions.createRedirect({
fromPath: from,
toPath: to,
isPermanent: true,
redirectInBrowser: true,
})
})
})
console.log(`${chalk.green("success")} create redirects`)
}
- Run when pages are being created
- Find files with
redirect_from
fields - Bail if error
- Iterate through results
- Run
createRedirect
action for each
Other plugins then take those redirects and configure them for your host. Gatsby Cloud's puts them in a _redirects.json
for example.
Funfact: this one broke because the slug field on Gatsby Cloud includes /blog/ and on Netlify it didn't ๐คทโโ๏ธ
Page redirects with _redirects
For known redirects, Netlify's _redirects
file is fast becoming an industry standard.
/serverless-handbok https://serverlesshandbook.dev
/reactd3js https://reactfordataviz.com
.
.
.
One redirect per line, from
on the left, to
on the right. Easy peasy.
Gatsby Cloud doesn't care about this file ๐ฉ
Instead you have to add this function to your gatsby-node.js
.
// gatsby-node.js
exports.onPreBootstrap = ({ actions }) => {
// read _redirects
// call createRedirect for each
const redirects = fs.readFileSync("./static/_redirects").toString()
for (const line of redirects.split("\n")) {
if (line.trim().length > 0) {
// found a redirect
const [fromPath, toPath] = line.trim().split(/\s+/)
actions.createRedirect({
fromPath,
toPath,
})
}
}
console.log(`${chalk.green("success")} create redirects from _redirects`)
}
- Runs after Gatsby inits, before other machinery
- Read the
static/_redirects
file - Iterate line by line
- Split by whitespace
- Call
createRedirect
action
And after all that I still have a :splat
config for my redirects that isn't working. Broken images ๐ฅฒ
Next time you change hosting, check everything my friend ๐
Cheers,
~Swizec
PS: lemme know if you find anything's broken
Continue reading about Use Netlify's _redirects on Gatsby Cloud
Semantically similar articles hand-picked by GPT-4
- Lessons from migrating a 14 year old blog with 1500 posts to Gatsby
- Moving 13 years of Wordpress blog to Gatsby Markdown
- How to export a large Wordpress site to Markdown
- Exploring NextJS with a headless CMS, pt4 โ CodeWithSwiz
- Building a small CMS with NextJS, pt2 โ CodeWithSwiz
Learned something new?
Read more Software Engineering Lessons from Production
I write articles with real insight into the career and skills of a modern software engineer. "Raw and honest from the heart!" as one reader described them. Fueled by lessons learned over 20 years of building production code for side-projects, small businesses, and hyper growth startups. Both successful and not.
Subscribe below ๐
Software Engineering Lessons from Production
Join Swizec's Newsletter and get insightful emails ๐ on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.
"Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. ๐"
Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.
Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.
Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help ๐ swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.
Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers ๐ ServerlessHandbook.dev
Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization
Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections
Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog
Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com
By the way, just in case no one has told you it yet today: I love and appreciate you for who you are โค๏ธ