Next.js 16 App Router中Google reCaptcha警告消除及实现规范咨询
解决Next.js 16 App Router中Google reCaptcha的
dangerouslySetInnerHTML警告 问题原因
你遇到的警告源于使用beforeInteractive策略的Script组件在服务端渲染时,不会生成客户端注入的脚本初始化代码;但在客户端 hydration 阶段,Next.js会自动添加这段代码,导致服务端与客户端的DOM内容不匹配,从而触发该警告。
解决方法
方法1:修改Script加载策略
将根布局中的strategy="beforeInteractive"改为strategy="lazyOnload",该策略会在客户端空闲时加载脚本,且不会在服务端渲染时生成额外内容,彻底避免 hydration 不匹配:
// src/app/randompage/layout.js import { Inter } from 'next/font/google'; import Script from 'next/script'; const inter = Inter({ subsets: ['latin'] }); export default function RootLayout({ children }) { return ( <html lang="en"> <head> <title>Random</title> <Script src="https://www.google.com/recaptcha/api.js?render=Key" strategy="lazyOnload" // 修改此处策略 /> </head> <body className={inter.className}> {children} </body> </html> ); }
由于你的handleRandom函数已使用grecaptcha.ready(),它会等待reCaptcha脚本加载完成后再执行逻辑,切换策略不会影响功能正常运行。
方法2:将Script移至客户端组件
把reCaptcha脚本的加载逻辑放到客户端组件(randompage/page.js)中,避免服务端渲染时处理脚本:
方式A:使用Next.js的Script组件
// src/app/randompage/page.js 'use client' import Script from 'next/script'; // ...其他导入 export default function RandomPage() { // ...你的组件状态和handleRandom函数 return ( <> <Script src="https://www.google.com/recaptcha/api.js?render=Key" strategy="lazyOnload" /> {/* 你的页面内容,如表单、按钮等 */} <button onClick={handleRandom}>执行操作</button> </> ); }
方式B:使用useEffect动态加载脚本
// src/app/randompage/page.js 'use client' import { useEffect } from 'react'; // ...其他导入 export default function RandomPage() { // ...你的组件状态和handleRandom函数 useEffect(() => { const script = document.createElement('script'); script.src = 'https://www.google.com/recaptcha/api.js?render=Key'; script.async = true; script.defer = true; document.head.appendChild(script); return () => { document.head.removeChild(script); }; }, []); return ( <> {/* 你的页面内容 */} <button onClick={handleRandom}>执行操作</button> </> ); }
关于无库实现的规范性
这种无库实现方式是规范且符合Google官方推荐的。Google reCaptcha官方文档本身就提供了直接加载脚本并调用grecaptcha.execute的原生方案,只要确保在grecaptcha.ready()回调中执行验证逻辑(你已做到),就能保证脚本加载完成后再操作,不会出现未定义错误。
在Next.js中,合理使用框架提供的Script组件或客户端侧动态脚本加载逻辑,就能兼顾SSR特性与reCaptcha的功能需求。
内容的提问来源于stack exchange,提问作者LupefiascoMosdef
相关产品推荐
相关产品推荐

