diff --git a/examples/with-relay/.env b/examples/with-relay/.env
new file mode 100644
index 00000000000000..4a4430d7e3f347
--- /dev/null
+++ b/examples/with-relay/.env
@@ -0,0 +1,2 @@
+# Use the StarWars GraphQL API: https://github.com/graphql/swapi-graphql
+NEXT_PUBLIC_RELAY_ENDPOINT=https://swapi-graphql.netlify.app/.netlify/functions/index
diff --git a/examples/with-relay/.gitignore b/examples/with-relay/.gitignore
new file mode 100644
index 00000000000000..d8f6e9330f5cea
--- /dev/null
+++ b/examples/with-relay/.gitignore
@@ -0,0 +1,39 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# next.js
+/.next/
+/out/
+
+# production
+/build
+
+# misc
+.DS_Store
+*.pem
+
+# debug
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# local env files
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+# vercel
+.vercel
+
+# relay
+__generated__/**
+!__generated__/.gitkeep
+schema.graphql
diff --git a/examples/with-relay/README.md b/examples/with-relay/README.md
new file mode 100644
index 00000000000000..f51d5ff63d6ebe
--- /dev/null
+++ b/examples/with-relay/README.md
@@ -0,0 +1,100 @@
+# Relay Hooks Example
+
+Relay is a JavaScript framework for building data-driven React applications.
+
+## About Relay
+
+- **Declarative:** Never again communicate with your data store using an imperative API. Simply declare your data requirements using GraphQL and let Relay figure out how and when to fetch your data.
+- **Colocation:** Queries live next to the views that rely on them, so you can easily reason about your app. Relay aggregates queries into efficient network requests to fetch only what you need.
+- **Mutations:** Relay lets you mutate data on the client and server using GraphQL mutations, and offers automatic data consistency, optimistic updates, and error handling.
+
+[Relay Hooks](https://relay.dev/) is the easiest-to-use, safest Relay API. It relies on suspense, and is safe to use in React concurrent mode.
+
+## Fetching Data
+
+> _Recommended reading: [Thinking in Relay](https://relay.dev/docs/principles-and-architecture/thinking-in-relay/)_
+
+This example demonstrates the two main strategies of optimised fetching data in
+a Next.js application using Relay Hooks:
+
+- **Page Data**: using Next.js's props loading methods `getStaticProps()`,
+ `getServerSideProps()`, or `getInitialProps()` with Relay Hooks.
+- **Lazy Data**: using Next.js's `next/dynamic` lazy component import in
+ parallel with Relay's `useQueryLoader()` for render-as-you-fetch data loading.
+
+### Page Data
+
+When using `getStaticProps()`, `getServerSideProps()`, or `getInitialProps()`,
+Next.js by default optimises network requests to fetch data + load JavaScript.
+
+By leveraging Relay's compiler, we are able to combine deeply nested data
+requirements into a single query executable within a `get*Props()` method,
+avoiding waterfalls and staggered data loads.
+
+See [`pages/index.jsx`](./pages/index.jsx) for an example of using
+`getStaticProps()` (_the same code should work for `getServerSideProps()` &
+`getInitialProps()`_)
+
+### Lazy Data
+
+There are times when your application loads a page with portions purposely
+hidden until user interaction or some other event occurs. An example is
+expanding a complex portion of the UI that is not often used; a better user
+experience is achieved by delaying the loading & execution of JavaScript until
+the user explicitly requests it. In Next.js, this is achieved using [dynamic
+imports](https://nextjs.org/docs/advanced-features/dynamic-import).
+
+To achieve optimised network requests for lazily (ie; _dynamically_) loaded
+components, the data can be fetched in parallel using Relay's
+[`useQueryLoader()` &
+`usePreloadedQuery()`](https://relay.dev/docs/api-reference/use-preloaded-query/),
+triggered at the same time as the user triggers the component load (eg; clicking
+"Expand" to show some complex UI).
+
+The example in [`pages/films.jsx`](./pages/films.jsx) builds on the concepts in
+`pages/index.jsx` using `useQueryLoader()`, `usePreloadedQuery()`, and
+`dynamic()` to optimise data & component loading to happen in parallel. Aka:
+render-as-you-fetch.
+
+## Deploy your own
+
+Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
+
+[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-relay&project-name=with-relay&repository-name=with-relay)
+
+## How to use
+
+Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
+
+```bash
+npx create-next-app --example with-relay with-relay-app
+# or
+yarn create next-app --example with-relay with-relay-app
+```
+
+Download schema introspection data from configured Relay endpoint (_this example
+uses the [StarWars GraphQL API](https://github.com/graphql/swapi-graphql)_):
+
+```bash
+npm run schema
+# or
+yarn schema
+```
+
+Run Relay ahead-of-time compilation (should be re-run after any edits to components that query data with Relay):
+
+```bash
+npm run relay
+# or
+yarn relay
+```
+
+Run the project:
+
+```bash
+npm run dev
+# or
+yarn dev
+```
+
+Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
diff --git a/examples/with-relay/__generated__/.gitkeep b/examples/with-relay/__generated__/.gitkeep
new file mode 100644
index 00000000000000..e69de29bb2d1d6
diff --git a/examples/with-relay/components/SWPilot.jsx b/examples/with-relay/components/SWPilot.jsx
new file mode 100644
index 00000000000000..5daf65c74d6cbc
--- /dev/null
+++ b/examples/with-relay/components/SWPilot.jsx
@@ -0,0 +1,23 @@
+import { graphql, useFragment } from 'react-relay'
+
+export const SWPilot = ({ pilot }) => {
+ const data = useFragment(
+ graphql`
+ fragment SWPilot_person on Person {
+ id
+ name
+ homeworld {
+ id
+ name
+ }
+ }
+ `,
+ pilot
+ )
+
+ return (
+
+ {data.name} ({data.homeworld.name})
+
+ )
+}
diff --git a/examples/with-relay/components/SWStarship.jsx b/examples/with-relay/components/SWStarship.jsx
new file mode 100644
index 00000000000000..43080d6a2150a0
--- /dev/null
+++ b/examples/with-relay/components/SWStarship.jsx
@@ -0,0 +1,41 @@
+import { graphql, useFragment } from 'react-relay'
+import { SWPilot } from './SWPilot'
+
+export const SWStarship = ({ starship }) => {
+ const data = useFragment(
+ graphql`
+ fragment SWStarship_starship on Starship {
+ id
+ name
+ pilotConnection {
+ totalCount
+ edges {
+ node {
+ id
+ ...SWPilot_person
+ }
+ }
+ }
+ }
+ `,
+ starship
+ )
+
+ return (
+
+ )
+}
diff --git a/examples/with-relay/lib/relay.jsx b/examples/with-relay/lib/relay.jsx
new file mode 100644
index 00000000000000..f03ac8c36bef57
--- /dev/null
+++ b/examples/with-relay/lib/relay.jsx
@@ -0,0 +1,90 @@
+import { useMemo } from 'react'
+import { Environment, Network, RecordSource, Store } from 'relay-runtime'
+
+export const RELAY_INITIAL_RECORDS_PROP = '__RELAY_INITIAL_RECORDS__'
+
+let relayEnvironment
+
+// Define a function that fetches the results of an operation (query/mutation/etc)
+// and returns its results as a Promise
+const fetchRelay = async (operation, variables) => {
+ const response = await fetch(process.env.NEXT_PUBLIC_RELAY_ENDPOINT, {
+ method: 'POST',
+ headers: {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ query: operation.text,
+ variables,
+ }),
+ })
+ return await response.json()
+}
+
+const createEnvironment = () =>
+ new Environment({
+ // Create a network layer from the fetch function
+ network: Network.create(fetchRelay),
+ store: new Store(new RecordSource()),
+ })
+
+// For use in non-react contexts: getServerSideProps, getStaticProps,
+// getInitialProps, pages/api routes.
+// Should be paired with finalizeRelay() with get*Props() methods.
+export const initializeRelay = (initialRecords) => {
+ // Create a network layer from the fetch function
+ const environment = relayEnvironment ?? createEnvironment()
+
+ // If your page has Next.js data fetching methods that use Relay, the initial records
+ // will get hydrated here
+ if (initialRecords) {
+ environment.getStore().publish(new RecordSource(initialRecords))
+ }
+
+ if (typeof window === 'undefined') {
+ // Tell relay to stop its normal garbage collection processes. This prevents
+ // data being lost between calling relay's `fetchQuery` and our
+ // `finalizeRelay` method below
+ environment.getStore().holdGC()
+
+ // For SSG and SSR always create a new Relay environment
+ return environment
+ }
+
+ // Create the Relay environment once in the client
+ if (!relayEnvironment) relayEnvironment = environment
+
+ return relayEnvironment
+}
+
+// Used to re-hydrate the relay cache in the client.
+// Works with getStaticProps() & getServerSideProps(). For use with
+// getInitialProps(), see finalizeRelayInitialProps()
+export const finalizeRelay = (environment, pageProps) => {
+ pageProps.props = pageProps.props ?? {}
+ pageProps.props[RELAY_INITIAL_RECORDS_PROP] = environment
+ .getStore()
+ .getSource()
+ .toJSON()
+
+ return pageProps
+}
+
+// Used to re-hydrate the relay cache in the client.
+// Works with getInitialProps(). For use with getServerSideProps() or
+// getStaticProps(), see finalizeRelay()
+export const finalizeRelayInitialProps = (environment, pageProps = {}) => {
+ pageProps[RELAY_INITIAL_RECORDS_PROP] = environment
+ .getStore()
+ .getSource()
+ .toJSON()
+
+ return pageProps
+}
+
+// For use in react components
+export const useRelayEnvironment = (pageProps) => {
+ const initialRecords = pageProps[RELAY_INITIAL_RECORDS_PROP]
+ return useMemo(() => initializeRelay(initialRecords), [initialRecords])
+}
diff --git a/examples/with-relay/next.config.js b/examples/with-relay/next.config.js
new file mode 100644
index 00000000000000..89574d57d1a6b3
--- /dev/null
+++ b/examples/with-relay/next.config.js
@@ -0,0 +1,7 @@
+const relay = require('./relay.config')
+
+module.exports = {
+ compiler: {
+ relay,
+ },
+}
diff --git a/examples/with-relay/package.json b/examples/with-relay/package.json
new file mode 100644
index 00000000000000..fcd36b116657a9
--- /dev/null
+++ b/examples/with-relay/package.json
@@ -0,0 +1,21 @@
+{
+ "private": true,
+ "scripts": {
+ "dev": "yarn run relay && next",
+ "build": "yarn run relay && next build",
+ "start": "yarn run relay && next start",
+ "relay": "yarn run relay-compiler $@",
+ "schema": "export $(grep -v '^#' .env | xargs) && get-graphql-schema $NEXT_PUBLIC_RELAY_ENDPOINT > schema.graphql"
+ },
+ "dependencies": {
+ "next": "latest",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "relay-runtime": "^13.2.0",
+ "react-relay": "^13.2.0"
+ },
+ "devDependencies": {
+ "get-graphql-schema": "^2.1.2",
+ "relay-compiler": "^13.2.0"
+ }
+}
diff --git a/examples/with-relay/pages/_app.jsx b/examples/with-relay/pages/_app.jsx
new file mode 100644
index 00000000000000..84c01eb52260c7
--- /dev/null
+++ b/examples/with-relay/pages/_app.jsx
@@ -0,0 +1,16 @@
+import { Suspense } from 'react'
+import { RelayEnvironmentProvider } from 'react-relay/hooks'
+
+import { useRelayEnvironment } from '../lib/relay'
+
+export default function App({ Component, pageProps }) {
+ const relayEnvironment = useRelayEnvironment(pageProps)
+
+ return (
+
+
+
+
+
+ )
+}
diff --git a/examples/with-relay/pages/films.jsx b/examples/with-relay/pages/films.jsx
new file mode 100644
index 00000000000000..206c6e053b01b7
--- /dev/null
+++ b/examples/with-relay/pages/films.jsx
@@ -0,0 +1,176 @@
+import { Fragment, Suspense } from 'react'
+import Link from 'next/link'
+import dynamic from 'next/dynamic'
+import {
+ graphql,
+ useQueryLoader,
+ usePreloadedQuery,
+ useFragment,
+ fetchQuery,
+} from 'react-relay'
+
+import { initializeRelay, finalizeRelay } from '../lib/relay'
+import { SWStarship } from '../components/SWStarship'
+
+// There's a lot going on in this file. It can be broken down into 2 main
+// sections, with their own data fetching strategies:
+//
+// 1. The data to load the initial page.
+// This is the same as pages/index.jsx; using fragments & fetchQuery().
+//
+// 2. The data & component loaded when a button is clicked.
+// a) We define a `LoadingCharacterTable` placeholder component for when
+// we're loading the component and data.
+// b) We tell Next.js that we'll dynamically import a `CharacterTable`
+// component.
+// c) The query `filmsCharacterQuery` uses a fragment defined in the
+// `CharacterTable` component.
+// d) `useQueryLoader()` gives us a `loadQuery()` method to lazily execute
+// the query defined in 2. c)
+// e) When the button is clicked, we start loading the dynamic component from
+// 2. b), and also trigger the query defined in 2. c) by calling
+// `loadQuery()` from 2. d). These two will run in parallel for maximum
+// performance
+// f) A boundary is rendered using the loading component in 2. a).
+// g) `usePreloadedQuery()` Attempts to read the result of calling
+// `loadQuery()` in 2. e). If the query hasn't completed yet, it will
+// trigger the boundary from 2. f)
+// h) Once 2. g) passes, React will attempt to render our dynamic component
+// from 2. b). If it's still loading, it will render the loading component
+// from 2. a).
+
+export async function getStaticProps() {
+ const environment = initializeRelay()
+
+ const result = await fetchQuery(
+ environment,
+ graphql`
+ query filmsPageQuery {
+ allFilms(first: 10) {
+ edges {
+ node {
+ id
+ ...films
+ }
+ }
+ }
+ }
+ `
+ ).toPromise()
+
+ // Helper function to hydrate the Relay cache client side on page load
+ return finalizeRelay(environment, {
+ props: {
+ // Return the results directly so the component can render immediately
+ allFilms: result.allFilms,
+ },
+ revalidate: 1,
+ })
+}
+
+// 2. a)
+const LoadingCharacterTable = () => 'Loading characters...'
+
+// 2. b)
+const CharacterTable = dynamic(
+ () =>
+ import('../components/character-table').then((mod) => mod.CharacterTable),
+ // NOTE: Can't use Next.js's suspense mode here; it will disable our ability
+ // to preload the component on button click.
+ // Instead, we use the same component here as we do for the Relay boundary.
+ { loading: LoadingCharacterTable }
+)
+
+// 2. c)
+const filmsCharacterQuery = graphql`
+ query filmsCharacterQuery($id: ID!) {
+ film(id: $id) {
+ ...characterTable_film
+ }
+ }
+`
+
+const FilmCharacterTable = ({ queryReference }) => {
+ // 2. g)
+ const data = usePreloadedQuery(filmsCharacterQuery, queryReference)
+ // 2. h)
+ return
+}
+
+// This component is always rendered on this page, so it's inlined into this
+// file. It could also be extracted into a separate file.
+const Film = ({ film }) => {
+ const data = useFragment(
+ // Notice this fragment does _not_ include any character information. That
+ // will be loaded lazily when the button is clicked
+ graphql`
+ fragment films on Film {
+ # NOTE: We also request the 'id' field in the root query for this page.
+ # Relay is smart enough to dedupe this field for us, reducing the
+ # scope of maintenance to where the field is read.
+ id
+ title
+ episodeID
+ }
+ `,
+ film
+ )
+
+ // 2. d)
+ const [queryReference, loadQuery] = useQueryLoader(filmsCharacterQuery)
+
+ return (
+
+ Episode {data.episodeID}: {data.title}
+
+ {queryReference == null ? (
+
+ ) : (
+ // 2. f)
+ // NOTE: The fallback component here is the same as used for the dynamic
+ // component's `loading` prop
+ }>
+
+
+ )}
+
+ )
+}
+
+const FilmsPage = ({ allFilms }) => (
+
+ {allStarships.edges.map(({ node: starship }) => (
+ // The `starship` prop gets read by Relay within the SWStarship
+ // component to hydrate the data required by the fragment in that
+ // component
+
+ ))}
+