Imed Adel.

How to Redirect Pages in Gatsby

Two methods to redirect pages in Gatsby

Use Redirect From Reach Router

You can redirect a page by importing Redirect from @reach/router to your page. Note that you do not have to install anything, as it comes shipped with Gatsby.

import React from "react"
import { Redirect } from "@reach/router"
const IndexPage = () => <Redirect to={`/en`} />
export default IndexPage

Use Window Location

First, check whether window is defined or not and then use window.location.replace() to do the redirection.

import React from "react"

if (typeof window !== `undefined`) window.location.replace(`/en`)
const IndexPage = () => {
	return <></>
}

export default IndexPage

Use createRedirect from Gatsby Actions

I kept this to the end because it didn’t work for me when I tried it. But Gatsby offers an action named createRedirect, which you can use in gatsby-node.js.

exports.createPages = ({ actions }) => {
	actions.createRedirect({
		fromPath: `/`,
		toPath: `/en`,
		isPermanent: `true`,
	})
}

Further Reading