Server rendered React ExpressJS frontend leaking users' Redux store data Server rendered React ExpressJS frontend leaking users' Redux store data express express

Server rendered React ExpressJS frontend leaking users' Redux store data


Variables defined in module scope have only one copy in the entire runtime environment. This means each node.js process has its own copy, and each browser tab/frame has its own copy. However, inside each tab or each process, there is only one copy. This means you cannot define your store as a module-level const and still have a new store for each user. You can solve it like this:

src/routes.js

import React from 'react';import { createStore, applyMiddleware, compose } from "redux";import routerConfig from "base/routes/routes";import thunk from "redux-thunk";import { rootReducer } from "base/reducers";let initialState = {};export function newUserEnv() {  const store = createStore(    rootReducer, initialState, compose(applyMiddleware(thunk))  );  const routes = routerConfig(store);  return { store, routes };}

server.js

import { newUserEnv } from 'routes';let getReduxPromise = (renderProps, request) => {  const { store } = newUserEnv();  let { query, params } = renderProps...

This creates a new store for each request and allows each user to have their own data. Note that if you need the same store from different modules, you'll need to pass it around. You can't just import { newUserEnv } because it will create a new one.