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' // highlight-line

const IndexPage = () => <Redirect to={`/en`} /> // highlight-line

export default IndexPage

Use Window Location

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

import React from 'react'

if (typeof window !== `undefined`) window.location.replace(`/en`) // highlight-line

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 }) => {
        fromPath: `/`,
        toPath: `/en`,
        isPermanent: `true`,

Further Reading