Skip to content

How to Set Up Redirects in Gatsby

Gatsby/

To create a redirect, you need to use createRedirect function in gatsby-node.js.

You can access it from the actions collection inside createPages Gatsby Node API function.

Start by creating a redirects.json file where you will keep your routes.

[
  {
    "from": "/posts/this-is-the-old-url/",
    "to": "/posts/the-new-destination-url/"
  }
]

Use from to specify the route from which you want to direct your users away. Specify the destination route inside the to property.

Now go ahead and import the redirects and use them inside the createPages API.

// gatsby-node.js

const redirects = require('./redirects.json');

exports.createPages = async ({ graphql, actions }) => {
  const { createRedirect } = actions;

  redirects.forEach(redirect => {
    createRedirect({
      fromPath: redirect.from,
      toPath: redirect.to,
    });
  });
};

This code creates a redirect for every entry inside the redirects array that you import from redirects.json.

Since redirects are server side, your hosting platform must handle them for you. For this reason, you can’t test redirects locally while developing.

The most popular hosting options — Gatsby Cloud and Netlify — handle redirects differently. Depending on your platform of choice, you need to install the needed plugin.

Redirects on Netlify

If you are using Netlify for hosting, you will need to install a plugin that handles the redirects for you.

npm i gatsby-plugin-netlify

Don’t forget to add it to your gatsby-config.js as well.

// gatsby-config.js

module.exports = {
  plugins: ['gatsby-plugin-netlify'],
};

Your redirects should now work after deploying your site on Netlify.

If you would like to redirect an entire subdirectory to a new location, you can use splats for that.

Let’s say you moved your blog posts from /blog/post-name to /posts/post-name. You can redirect all your old /blog/* URLs to /posts.

// redirects.json

[
  {
    "from": "/blog/*",
    "to": "/posts/:splat"
  }
]

You can turn to Netlify’s documentation article Redirect options for more information.

Redirects on Gatsby Cloud

To have your redirects work on Gatsby Cloud, you need to install the gatsby-plugin-gatsby-cloud plugin.

npm i gatsby-plugin-gatsby-cloud

And add it to your gatsby-config.js.

// gatsby-config.js

module.exports = {
  plugins: ['gatsby-plugin-netlify'],
};

The syntax for splat redirects on Gatsby Cloud differs from Netlify. To redirect all requests from /blog/ subdirectory to /posts/ subdirectory, use an asterisk (*).

// redirects.json

[
  {
    "from": "/blog/*",
    "to": "/posts/*"
  }
]

Check out the Working with Redirects and Rewrites article to learn about other options on Gatsby Cloud redirects.