How to use Relay with Next.js and TypeScript

Matt Lim
JavaScript in Plain English
2 min readJun 12, 2021

--

The Problem

If you have some Relay code like this:

import { Suspense } from "react";
import { graphql } from "relay-runtime";
import { useLazyLoadQuery } from "react-relay";
const RelayTestQuery = graphql`
query RelayTestQuery {
viewer {
id
}
}
`;
function RelayTestInner() {
const data = useLazyLoadQuery(RelayTestQuery, {
variables: {},
});
return <div>hi</div>;
}
export default function RelayTest() {
return (
<Suspense fallback={<div>Loading</div>}>
<RelayTestInner />
</Suspense>
);
}

And you render it like this:

export default function Home() {
return (
<RelayEnvironmentProvider environment={RelayEnvironment}>
<RelayTest />
</RelayEnvironmentProvider>
);
}

then you’ll get this error:

ReactDOMServer does not yet support Suspense.

The Solution

Dynamic Imports

To fix this, you can use RelayTestDynamic instead:

import dynamic from "next/dynamic";const RelayTestDynamic = dynamic(() => import("./RelayTest"), {
ssr: false,
});
export default RelayTestDynamic;

It’s kind of annoying to do this though, and if your components that use Relay are visible on the initial load (they probably are), it’s bad for performance (now the browser needs to make another request for JS that could’ve been sent down in the initial response).

Alpha Versions

Alternatively, you can use the alpha versions of react and react-dom.

yarn add react@alpha react-dom@alpha

With the alpha versions, the dynamic import is no longer required. It results in some warnings, but it seems to work fine.

About TSConfig

https://github.com/relay-tools/relay-compiler-language-typescript#typescript mentions the following:

Also be sure to configure the TypeScript compiler to transpile to es2015 modules and leave transpilation to commonjs modules up to Babel with the following tsconfig.json settings:

I found that to be unnecessary. Not sure why, maybe it doesn’t apply when using Relay hooks?

Check out these repos for examples.

TLDR: Either use dynamic imports or use the React 18 alpha https://github.com/reactwg/react-18/discussions/9

--

--

Software Engineer. Tweeting @pencilflip. Mediocre boulderer, amateur tennis player, terrible at Avalon. https://www.mattlim.me/