Gatsby结合react-hook-form与react-hook-recaptcha重载报SSR错误如何解决?
Gatsby表单集成ReCaptcha SSR错误解决方案
问题根因
Gatsby在构建阶段会执行SSR(服务端渲染),Node环境不存在window等浏览器API,你使用的react-hook-recaptcha库默认会在初始化时访问浏览器全局对象,导致服务端渲染阶段报错。
修复步骤
1. 将表单组件改为仅客户端加载
Gatsby默认所有页面组件都会走SSR,你需要把表单组件抽离为独立组件,通过动态导入的方式关闭SSR:
首先安装@loadable/component(Gatsby官方推荐的动态加载方案,支持SSR场景):
npm install @loadable/component # 或者 yarn add @loadable/component
然后修改你的页面文件(比如src/pages/contact.js):
import * as React from "react" import { Layout } from "../components/layout" import loadable from "@loadable/component" // 动态导入表单组件,关闭SSR const ContactForm = loadable(() => import("../components/ContactForm"), { ssr: false, fallback: <div>表单加载中...</div> }) export default function ContactPage() { return ( <Layout> <ContactForm /> </Layout> ) }
注意:需要把你现有的表单组件代码从pages目录移动到components目录,避免被Gatsby当作页面直接走SSR渲染。
2. 优化自定义hook的浏览器API访问逻辑
修改useformWithRecaptcha.js,给所有访问grecaptcha的逻辑加客户端环境判断,避免服务端执行时报错:
const executeRecaptcha = (e) => { e.preventDefault() // 新增环境判断,服务端直接跳过执行 if (typeof window === "undefined" || !window.grecaptcha || recaptchaWidget === null) return window.grecaptcha.reset(recaptchaWidget) window.grecaptcha.execute(recaptchaWidget) } const resetRecaptcha = () => { if (typeof window === "undefined" || !window.grecaptcha || recaptchaWidget === null) return window.grecaptcha.reset(recaptchaWidget) }
3. 可选:手动加载ReCaptcha脚本(第三方库兼容性问题时使用)
如果修改后仍有问题,可以弃用react-hook-recaptcha,改为手动控制脚本加载逻辑,可控性更高:
在useformWithRecaptcha.js中新增脚本加载逻辑:
useEffect(() => { if (typeof window === "undefined" || window.grecaptcha) return // 手动注入recaptcha脚本 const script = document.createElement("script") script.src = "https://www.google.com/recaptcha/api.js?render=explicit" script.async = true script.defer = true document.body.appendChild(script) }, [])
验证
修改完成后重新执行gatsby develop,刷新页面不会再出现SSR报错,表单提交时ReCaptcha可以正常生成校验令牌。
内容的提问来源于stack exchange,提问作者user10229330
相关产品推荐
相关产品推荐

