This is a PoC for combining Next.js App Router and Relay.
As of April 2024, there is an official example combining Next.js App Router with Relay.
However, this example is mostly composed of Client Components. This is because it uses useFragment
for data masking. useFragment
is a React Hook and cannot be used in Server Components. Therefore, most of the component tree must be made up of Client Components.
This PoC demonstrates how to combine Next.js App Router with Relay while keeping more components as Server Components.
$ npm i
$ npm run gen
$ npm run dev
$ open http://localhost:3000
readInlineData
instead of useFragment
With readInlineData
, you can achieve data masking similar to useFragment
. Additionally, readInlineData
can be used in Server Components as it is not a React Hook. Therefore, this PoC uses readInlineData
as much as possible.
fetchQuery
instead of loadSerializableQuery
and usePreloadedQuery
In the official example, query data is fetched as follows:
loadSerializableQuery
useSerializablePreloadedQuery
to get a PreloadedQuery
.PreloadedQuery
to usePreloadedQuery
to access the query data (FooQuery$data
).useFragment
in the Client Component to read the query data.This approach requires the use of `usePreloadedQuery', which requires client components.
Instead, in this PoC, query data is fetched as follows:
fetchQuery
.
FooQuery$data
) of the query.readInlineData
.This allows the Server Component to fetch queries and read data.
QueryResponseCache
In order for the Client Component to also read the query data fetched by the Server Component, it must be cached in a location accessible by the client.
The official example uses QueryResponseCache
to cache the query data. However, the code is a bit more complex.
In this PoC, we cache query data in a Store
. It is the standard storage to cache query results in Relay. This simplifies the code.