在 SSR 中如何为每个请求创建独立 Store?
解读
国内主流公司(阿里、美团、字节等)的 Node 渲染层普遍采用 “多进程 + 短生命周期” 的架构:一次 HTTP 请求对应一次 renderToString。Redux 的 单一 Store 原则在浏览器端天然成立,但在服务端如果全局复用同一个 Store,会导致并发请求之间状态污染,A 请求把 B 请求的数据带出去,引发 “串台” 事故。因此面试想考察的是:你是否理解 “服务端 Store 必须随请求诞生、随请求消亡” 这一铁律,并能在工程化层面给出可落地的代码范式。
知识点
- Store 创建函数工厂化:把 createStore 封装成
configureStore(req),每次调用返回全新实例。 - 上下文隔离:在 Express/Koa 中间件里把 Store 挂到
ctx.state.store或req.reduxStore,确保同一次请求内所有逻辑都能拿到同一份 Store。 - 脱水与注水:服务端 render 前
const preloadedState = store.getState(),序列化到 HTML 的window.__INITIAL_STATE__;浏览器端createStore(preloadedState)完成状态接续。 - 内存泄漏防控:render 完成后手动
store.dispatch(resetAction)或干脆让 Store 随请求结束被 GC,防止闭包持有大对象。 - 数据预取范式:
loadData静态方法 +matchRoutes做按需派发,保证 “先等待所有异步 Action 完成再 render”,否则会出现服务端 HTML 与客户端虚拟 DOM 不一致导致的 “闪屏” 或 “hydration 警告”。
答案
- 封装工厂函数
// src/store/configureStore.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
export default function configureStore(initialState = {}) {
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk)
);
return store;
}
- 请求级中间件
// server/middleware/reduxStore.js
import configureStore from '../../src/store/configureStore';
export default function reduxStore() {
return async (ctx, next) => {
const store = configureStore();
ctx.state.store = store; // Koa 风格
await next();
};
}
- 路由级数据预取
// server/router.js
import { matchRoutes } from 'react-router-config';
import routes from '../src/routes';
router.get('*', reduxStore(), async ctx => {
const { store } = ctx.state;
const branch = matchRoutes(routes, ctx.url);
const promises = branch
.filter(({ route }) => route.loadData)
.map(({ route }) => store.dispatch(route.loadData(ctx)));
await Promise.all(promises);
const html = renderToString(
<Provider store={store}>
<StaticRouter location={ctx.url} context={{}}>
{renderRoutes(routes)}
</StaticRouter>
</Provider>
);
const state = JSON.stringify(store.getState()).replace(/</g, '\\u003c');
ctx.body = `
<!doctype html>
<html>
<head><meta charset="utf-8"/></head>
<body>
<div id="root">${html}</div>
<script>window.__INITIAL_STATE__ = ${state}</script>
<script src="/client.js"></script>
</body>
</html>
`;
});
- 客户端接续
// client/index.js
import configureStore from '../src/store/configureStore';
const store = configureStore(window.__INITIAL_STATE__);
hydrate(<Provider store={store}><BrowserRouter>{renderRoutes(routes)}</BrowserRouter></Provider>, document.getElementById('root'));
通过以上四步,每个 HTTP 请求独享一份 Store,彻底杜绝并发污染,同时保证服务端与浏览器端状态同源,满足国内大厂对 “零 hydration 错误” 的硬性要求。
拓展思考
- 多实例缓存池:在高并发场景下,频繁
createStore会带来短暂 GC 压力,可预生成 Store 对象池 并结合Object.assign(store.getState(), initialState)做复用,但需权衡 “池化” 带来的复杂度与收益。 - 微前端 SSR:当子应用独立维护 Redux 时,需在 “请求级运行时” 里做 Store 命名空间隔离,防止主应用与子应用 Reducer key 冲突;国内解法常借助 “运行时重写 combineReducers” 或 “Symbol(key) 命名”。
- Serverless 场景:函数实例可复用,全局变量跨请求存活,必须保证
configureStore在 handler 内部调用,且 禁止 把 Store 挂在模块顶层;否则会出现 “冷启动缓存污染”,在阿里 FC、腾讯 SCF 环境均已踩坑。