Apollo SchemaLink
with context support. Useful for Next.js apps with universal Apollo GraphQL client that require context (for example field authorization).
Install
pnpm i better-schema-link @apollo/client graphql
Example
import { ApolloClient, InMemoryCache, ApolloLink, ServerError } from '@apollo/client'
const createIsomorphLink = () => {
if (typeof window === 'undefined') {
const { SchemaLink } = require('better-schema-link')
const { schema } = require('../graphql/schema')
const context = require('../graphql/context')
return new SchemaLink({ schema, context })
} else {
const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin'
})
}
}
export const createApolloClient = () =>
new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(),
cache: new InMemoryCache()
})