Next.js 是一个非常流行的 React 框架,它提供了开箱即用的服务端渲染(Server-Side Rendering, SSR)能力,我们可以很轻松地借助 Next.js 实现 SSR,并部署到 Vercel 上。然而,Vercel 在国内没有服务节点,SSR 时通过 Vercel 服务器请求国内的服务接口存在一定比例的请求失败,影响到了页面的渲染。因此,我们需要增加客户端渲染(Client-Side Rendering, CSR)的逻辑作为兜底,以提升渲染成功率。
在 Next.js 中我们通过给页面组件增加 getServerSideProps 方法,即可触发 SSR。例如,我们根据页面 URL 上的路径参数 id 调用接口获取详细信息,并将数据提供给页面组件方法渲染。代码如下:
 interface Props {  detail: Detail;}
async function getServerSideProps(context: GetServerSidePropsContext): Promise<{ props: Props }> {  const { id } = context.params;  const detail = await getDetail(id);
  return {    props: {      detail,    },  };}
   复制代码
 
Next.js 会传递 context 给 getServerSideProps 方法,其中包括了路由及请求参数信息;我们通过返回一个包含 props 的对象,将获取到的数据通过 props 提供给页面组件在服务端渲染。
 const Page: React.FC<Props> = props => {  return <div>detail 的渲染逻辑 {props.detail}</div>;};
   复制代码
 
由此可见,页面组件强依赖了服务端传递 props 的数据,如果请求失败势必导致页面无法正常渲染。
实现 CSR 的兜底逻辑
首先,我们需要对 getServerSideProps 进行改造,增加请求出错时的容错:
 async function getServerSideProps(context: GetServerSidePropsContext): Promise<{ props: Props | {} }> {  const { id } = context.params;    try {    const detail = await getDetail(id);
    return {      props: {        detail,      },    };  } catch {    return {      props: {},    };  }}
   复制代码
 
当请求失败时,我们通过 catch 捕捉到错误,并将 props 设置为 {},以通知组件获取数据失败。我们在组件中利用 useEffect 再次发起请求:
 const Page: React.FC<Props> = props => {  const isEmptyProps = Object.keys(props).length === 0;  const [detail, setDetail] = useState(props.detail);  const router = useRouter();
  useEffect(() => {    if (isEmptyProps) {      const { id } = router.query;
      getDetail(id).then(props => setDetail(props.detail));    }  }, []);
  return <div>detail 的渲染逻辑 {detail}</div>;};
   复制代码
 
我们通过判断 props.detail 是否为空对象,决定是否在浏览器端是否再次发起请求,请求参数 id 可以通过 Next.js 提供的 next/router 中 useRouter 获取。数据获取成功后,保存在组件的 State 中。
至此我们就完成了页面组件从 SSR 到 CSR 的降级。但是,我们有很多个页面都需要支持降级,逐一改造的成本太高,我们需要将这些逻辑进行抽象。
抽象降级的逻辑
从上面的实现过程来看,降级的逻辑主要分为两步:
- getServerSideProps增加错误捕获,出错时- props返回- {}
 
 
- 页面组件中判断 - props是否为空对象,如果是则再次发起请求获取数据
 
针对这两个步骤,我们可以分别进行抽象:
抽象 SSR 错误捕获
我们可以通过定义一个工厂函数,用来在原 getServerSideProps 上增加错误捕获:
  function createGetServerSidePropsFunction<F = GetServerSideProps>(getServerSideProps: F): F {    return async (context: GetServerSidePropsContext) => {      try {        return await getServerSideProps(context);      } catch {        return {          props: {},        };      }    };  }
   复制代码
 
再将这个工厂函数产生的函数导出:
 export const getServerSideProps = createGetServerSidePropsFunction(getServerSidePropsOrigin);
   复制代码
 抽象 CSR 数据请求
我们可以实现一个高阶组件(Higher-Order Components, HOC)将这部分逻辑抽象:
 function withCSR<C extends React.FC<any>, P extends object = React.ComponentProps<C>>(component: C, getServerSideProps: GetServerSideProps) {  const HoC = (props: P) => {    const [newProps, setNewProps] = useState<P>(props);    const router = useRouter();    const isPropsEmpty = Object.keys(props).length === 0;
    useEffect(() => {      if (isPropsEmpty) {        const context: GetServerSidePropsContext = {          locale: router.locale,          locales: router.locales,          defaultLocale: router.defaultLocale,          params: router.query,          query: router.query,          resolvedUrl: router.asPath,          req: {} as unknown,          res: {} as unknown,        };
        getServerSideProps(context).then(setNewProps);      }    }, []);
    if (newProps) {      return React.createElement(component, newProps);    }
    return null;  };
  HoC.displayName = `Hoc(${component.name})`;
  return HoC;}
   复制代码
 
逻辑与前面的实现基本一致,在高阶组件中判断如果 SSR 失败,我们在浏览器端再次调用 getServerSideProps 发起请求,此时我们需要构造一个与 Next.js 一致的 context,这里我们选择从 next/router 上获取相关信息并构造。最后,我们将页面组件传入高阶组件,返回一个新的页面组件并导出。
 export default withCSR(Page, getServerSidePropsOrigin);
   复制代码
 页面组件的接入
完成这两步抽象后,我们的页面组件降级的实现变得非常简单,在不需要修改页面组件和 getServerSideProps 的基础上,只需要增加以下几行:
 import { withCSR, getServerSideProps } from '../ssr-fallback';
export const getServerSideProps = createGetServerSidePropsFunction(getServerSidePropsOrigin);
export default withCSR(Page, getServerSidePropsOrigin);
   复制代码
 
至此,我们就实现了从 SSR 到 CSR 的优雅降级。
进一步抽象成 NPM 包
我们将以上逻辑抽象成了 NPM 包 next-ssr-fallback,并进一步抽象了 SSRFallback 类,简化 getServerSideProps 的传递。使用方式如下:
 import FallbackSSR from 'next-ssr-fallback';
const fallbackSSR = new FallbackSSR({  getServerSideProps: getServerSidePropsOrigin,});
export const getServerSideProps = fallbackSSR.createGetServerSidePropsFunction();
export default fallbackSSR.withCSR(Page);
   复制代码
 
next-ssr-fallback 的 GitHub 仓库:https://github.com/crazyurus/next-ssr-fallback
这里也有一个接入了 next-ssr-fallback 的 Next.js 项目 recruit-pc 供参考,项目部署在 Vercel 上 https://recruit-pc.vercel.app
总结
我们在 Next.js 中遇到了 SSR 渲染失败的问题时,选择了降级到 CSR 以提升渲染成功率,并将这部分实现逻辑抽象为 next-ssr-fallback 以复用到其它项目,实现更为优雅的降级。
如果有其它有关 SSR 降级的实践,欢迎分享
评论