Created
January 12, 2022 22:43
-
-
Save jckw/4e101f352f272f3239df1c8d6fadad38 to your computer and use it in GitHub Desktop.
GraphQL Utils for using Urql SSR with Next.js and getServerSideProps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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