如何从 NextJS 服务器水合 Apollo 客户端

Mar*_*nov 6 javascript apollo reactjs react-apollo next.js

我正在使用带有 Apollo 客户端的自定义 NextJS 服务器。我想在服务器端获取 GraphQL 数据,然后将其发送到客户端。我本来可以做到这一点,但客户端再次获取它。据我所知,Apollo 缓存仅在服务器上可用,然后需要发送到客户端并从那里恢复。

Apollo文档提到了 SSR,但我不想使用 Apollo 客户端完全渲染我的应用程序,我想使用 NextJS,我只想从 Apollo 客户端获取数据并将其手动注入到 HTML 中以将其恢复到客户。我查看了一些使用 Apollo 的 NextJS 示例,但没有一个示例展示了如何准确地做到这一点。

这是我的自定义请求处理程序:

const app = next({ dev: process.env.NODE_ENV !== 'production' });

const customHandler = async (req, res) => {
  const rendered = await app.renderToHTML(req, res, req.path, req.query);
  // somehow get the data from the apollo cache and inject it in the rendered html
  res.send(rendered);
}
Run Code Online (Sandbox Code Playgroud)

Sub*_*ash 0

当您在服务器中创建 时ApolloClient,您可以传递initialState来水合缓存。

const createApolloClient = ({ initialState, headers }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
    });

export default withApollo(PageComponent, { ssr = true } = {}) => {

  const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
    const client = apolloClient || createApolloClient({ initialState: apolloState, headers: {} });

     ... rest of your code. 
  });
});

Run Code Online (Sandbox Code Playgroud)

我为此创建了一个名为 的包nextjs-with-apollo。看看https://github.com/adikari/nextjs-with-apollo。安装该软件包后,创建一个 HOC。

// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const GRAPHQL_URL = 'https://your-graphql-url';

const createApolloClient = ({ initialState, headers }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
    });

export default withApollo(createApolloClient);
Run Code Online (Sandbox Code Playgroud)

然后您可以将 hoc 用于您的next页面。

import React from 'react';
import { useQuery } from '@apollo/react-hooks';

import withApollo from 'hocs/withApollo';

const QUERY = gql`
  query Profile {
    profile {
      name
      displayname
    }
  }
`;

const ProfilePage = () => {
  const { loading, error, data } = useQuery(PROFILE_QUERY);

  if (loading) {
    return <p>loading..</p>;
  }

  if (error) {
    return JSON.stringify(error);
  }

  return (
    <>
      <p>user name: {data.profile.displayname}</p>
      <p>name: {data.profile.name}</p>
    </>
  );
};

export default withApollo(ProfilePage);
Run Code Online (Sandbox Code Playgroud)