Как подключить apollo client в Nextjs
Пытаюсь подключить Apollo Client на Nextjs, но выходит ошибка:
Error: Unable to find native implementation, or alternative implementation for WebSocket!
Код подлючения:
export default function App({ Component, pageProps }) {
const httpLink = new HttpLink({
uri: 'http://localhost:8080/graphql'
});
const wsLink = new WebSocketLink({
uri: `ws://localhost:8080/graphql`,
options: {
reconnect: true
}
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink,
);
const apolloClient = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
})
return (
<ApolloProvider client={apolloClient}>
<Component {...pageProps} />
</ApolloProvider>
)
}
На чистом react все без проблем запускается, а в next не хочет.
Ответы (1 шт):
Автор решения: Michael Shcherbakov
→ Ссылка
Нашел пример, который оставили разработчики Nextjs по graphql.
Cсылка: https://github.com/vercel/next.js/tree/canary/examples/with-apollo
И дополнил его подключением через ws.
Вот код:
const wsLink = typeof window !== 'undefined' ? new WebSocketLink({
uri: 'ws://localhost:8080/graphql',
options: {
reconnect: true
}
}) : null;
const httplink = new HttpLink({
uri: 'http://localhost:8080/graphql',
credentials: 'same-origin'
});
const link = typeof window !== 'undefined' ? split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httplink,
) : httplink;
const apolloClient = new ApolloClient({
link,
cache: new InMemoryCache()
});
Проблема была в том, что я пытался его подключить на сервере, что и вело к ошибке. Но после исправления клиент успешно смог подключиться.
