Skip to content

Instantly share code, notes, and snippets.

@jckw
Created January 12, 2022 22:43
Show Gist options
  • Save jckw/4e101f352f272f3239df1c8d6fadad38 to your computer and use it in GitHub Desktop.
Save jckw/4e101f352f272f3239df1c8d6fadad38 to your computer and use it in GitHub Desktop.
GraphQL Utils for using Urql SSR with Next.js and getServerSideProps
import {
GetServerSideProps,
GetServerSidePropsContext,
GetServerSidePropsResult,
NextPage,
} from 'next'
import { initUrqlClient, SSRData, withUrqlClient } from 'next-urql'
import {
cacheExchange,
Client,
dedupExchange,
fetchExchange,
ssrExchange,
} from 'urql'
type GqlGetServerSidePropsContext = GetServerSidePropsContext & {
client: Client | null
}
type ExpectedProps = {
urqlState: SSRData
}
export const gqlProps =
(
f: (
ctx: GqlGetServerSidePropsContext
) => Promise<GetServerSidePropsResult<ExpectedProps> | void>
): GetServerSideProps<ExpectedProps> =>
async (context) => {
const { req } = context
const { headers } = req
const ssrCache = ssrExchange({ isClient: false })
const client = initUrqlClient(
{
url: 'http://localhost:8000/graphql',
fetchOptions: {
headers: {
cookie: headers.cookie || '',
},
},
exchanges: [dedupExchange, cacheExchange, ssrCache, fetchExchange],
},
false
)
const res = await f({ client, ...context })
const baseProps = { urqlState: ssrCache.extractData() }
if (res) {
return {
...res,
props: {
...baseProps,
...((res as { [key: string]: any }).props || {}),
},
}
}
return {
props: baseProps,
}
}
export const withGqlClient = (component: NextPage) =>
withUrqlClient(
() => ({
url: 'http://localhost:8000/graphql',
fetchOptions: { credentials: 'include' },
}),
{ ssr: false }
)(component)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment