在 Next.js 中如何把预取数据序列化到 window.__PRELOADED_STATE__?
解读
这道题考察的是 “同构渲染” 场景下 Redux 初始数据的注入与反序列化流程,是 国内中高级 React/Next.js 岗位 面试的高频考点。
面试官真正想听的是:
- 你能在 getServerSideProps / getInitialProps 里把 Store 快照安全地吐到 HTML;
- 你清楚 “序列化-反序列化” 环节的安全、性能、兼容性陷阱;
- 你能给出 可落地的代码骨架,而不是只背概念。
知识点
- Next.js 数据预取钩子:getServerSideProps(SSR)、getInitialProps(兼容 SSR/SSG)。
- Redux 快照提取:store.getState() 得到纯对象。
- 序列化安全:必须用 serialize-javascript 防 XSS,不能用 JSON.stringify 裸写。
- 注水位置:在 _document.tsx 的
<Head>或<body>尾部插入脚本,保证在 React 渲染前执行。 - 客户端脱水:createStore 时以 window.PRELOADED_STATE 为 preloadedState,并立即 delete window.PRELOADED_STATE 避免重复注水。
- 性能细节:快照过大会阻塞首屏,需 按需裁剪 或做 分块注水(code-splitting + slice)。
- TS 类型:声明全局接口
Window { __PRELOADED_STATE__?: RootState; }保证类型安全。
答案
- 服务端(以 getServerSideProps 为例)
// pages/index.tsx
import { serialize } from 'serialize-javascript';
import { Provider } from 'react-redux';
import { makeStore } from '../store';
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const store = makeStore();
// 1. 根据路由参数或 cookie 预拉数据
await store.dispatch(fetchUser(ctx.req.headers.cookie));
// 2. 提取快照
const preloadedState = store.getState();
// 3. 序列化并转义
const serializedState = serialize(preloadedState, { isJSON: true });
// 4. 注入到页面级 props
return {
props: { serializedState },
};
};
- 自定义 Document 注入脚本
// pages/_document.tsx
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document';
class MyDocument extends Document<{ serializedState: string }> {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
const pageProps = ctx.renderPage().htmlProps;
// 把页面级 props 透传过来
const serializedState = (ctx.renderPage().initialProps as any).serializedState || '{}';
return { ...initialProps, serializedState };
}
render() {
return (
<Html>
<Head />
<body>
<script
dangerouslySetInnerHTML={{
__html: `window.__PRELOADED_STATE__=${this.props.serializedState}`,
}}
/>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
- 客户端脱水
// store/index.ts
const preloadedState =
typeof window !== 'undefined' && window.__PRELOADED_STATE__
? window.__PRELOADED_STATE__
: undefined;
export const store = configureStore({
reducer: rootReducer,
preloadedState,
});
if (typeof window !== 'undefined') {
delete window.__PRELOADED_STATE__;
}
至此,“服务端预取 → 序列化 → 注水 → 客户端脱水” 闭环完成,Redux 初始状态与 HTML 同步到达浏览器,首屏直出与客户端 hydration 零抖动。
拓展思考
- 双端数据一致性:若 SSR 与 CSR 拉取接口域名不同,需统一 BASE_URL 环境变量,避免状态不一致导致 hydration 错误。
- 大体积快照优化:
– 只把 首屏依赖的 slice 序列化,其余在客户端再拉;
– 使用 @next/bundle-analyzer 量化注水体积,超过 50 KB 即告警。 - 安全加固:
– 禁止把 用户输入 直接塞进 preloadedState;
– 对 cookie/token 类敏感字段做 白名单过滤。 - SSG 场景:getStaticProps 同样适用,但需保证 build 时快照可序列化,不能包含函数、Date、Map 等。
- Redux Toolkit 新范式:可直接用 configureStore 的
preloadedState参数,无需手写 createStore,但序列化逻辑不变。