RSS Amplifier

Joel M Turner · Nov 2, 2021

Gatsby Client-Side External Redirect

0
Sign in to vote or save

Joel M Turner · Joel M Turner

Author: Joel M Turner Published Updated


We had a case where we needed to set up a redirect on the client side of Gatsby but we didn’t want to spin up a lambda to handle this one case. A redirect like this wouldn’t be a problem with some of the hosts out there, but we’re just using s3 and Cloudfront for this site.

To set up a quick redirect on the client we can send a redirect link through page context and handle the window location in a useEffect.

{

path: "/path",

component: resolve(__dirname, "../src/templates/EmptyPage.tsx"),

context: {

redirectTo:

"https://someawesomewebsite.com/newLink",

},

},

import React, { useEffect } from "react";

function isClient() {

return typeof window === "object";

}

export default function EmptyPage({ pageContext }) {

useEffect(() => {

if (isClient() && pageContext?.redirectTo) {

window.location.href = pageContext.redirectTo;

}

}, []);

return <div />;

}

Read the original on joelmturner.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.