【问题标题】:Implementing Apollo Client for NextJS but getting Cannot read property 'WebSocket' of undefined为 NextJS 实现 Apollo 客户端,但无法读取未定义的属性“WebSocket”
【发布时间】:2020-03-04 17:02:31
【问题描述】:

看了各种视频和阅读文章后,决定从普通的 React 切换到 NextJS。我目前正在尝试实现 Apollo Client,但遇到了这个(标题)错误,希望能得到一些帮助。我的 withData 当前设置的方式是

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { hasSubscription } from '@jumpn/utils-graphql';
import * as AbsintheSocket from '@absinthe/socket';
import withApollo from 'next-with-apollo';
import { createAbsintheSocketLink } from '@absinthe/socket-apollo-link';
import { Socket as PhoenixSocket } from 'phoenix';

let apolloClient = null;

const HTTP_ENDPOINT = 'http://localhost:4000/api/v1/graphiql';

const WS_ENDPOINT = 'ws://localhost:4000/api/v1/socket';

const httpLink = createHttpLink({
    url: HTTP_ENDPOINT
});

const socketLink = createAbsintheSocketLink(AbsintheSocket.create(new PhoenixSocket(WS_ENDPOINT)));

const authLink = setContext((_, { headers }) => {
    const token = localStorage.getItem('auth-item');
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : ''
        }
    };
});

const link = new ApolloLink.split(
    (operation) => hasSubscription(operation.query),
    socketLink,
    authLink.concat(httpLink)
);

const create = (initialState) => {
    return new ApolloClient({
        link: link,
        cache: new InMemoryCache().restore(initialState || {})
    });
};

const initApollo = (initialState) => {
    // Make sure to create a new client for every server-side request so that data
    // isn't shared between connections (which would be bad)
    if (typeof window === 'undefined') {
        return create(initialState);
    }

    // Reuse client on the client-side
    if (!apolloClient) {
        apolloClient = create(initialState);
    }

    return apolloClient;
};

export default withApollo(initApollo);

感谢所有帮助,以了解我做错了什么以及应该有更好的方法。

【问题讨论】:

    标签: reactjs next.js apollo-client


    【解决方案1】:

    问题是因为 nextJs 将在服务器中运行上面的代码,而WebSocket 是仅存在于浏览器中的属性,要修复此问题,您可以这样做:

    const socketLink =
      process.browser &&
      createAbsintheSocketLink(
        AbsintheSocket.create(
          new PhoenixSocket(WS_URI)
        )
      )
    

    通过检查process.browser,您可以确保该函数仅在客户端执行。

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2021-11-21
      • 2021-03-15
      相关资源
      最近更新 更多