joelmturner pyramid logo

About

Blog

Illustration

TIL

Uses

About

Blog

Illustration

TIL

Uses

Gatsby Client-Side External Redirect

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 />;
}

Discuss this article on Twitter

Category:

dev

© 2012-2023, built with Next.js and Chakra UI

InstagramtwitterlinkedIngithubjoelmturner's DEV Profilejoelmturner's Mastodon Profile