Blog>
Snippets

Preserving Store Integrity with Object.create(null)

Demonstrate how to prevent unwarranted prototype chain access by using Object.create(null) when resetting the Redux state.
function createStore(reducer) {
  let state;

  function dispatch(action) {
    state = reducer(state, action);
    // Other code to update subscribers...
  }

  function getState() {
    return state;
  }

  // Reset the state with a prototype-less object to avoid prototype pollution
  function resetState() {
    state = Object.create(null);
  }

  return {
    dispatch,
    getState,
    resetState
  };
}
This code snippet demonstrates how to create a simple Redux-like store with a `resetState` function that resets the state to an object without a prototype. This is to prevent prototype pollution and ensure no unintended properties are accessible from the object's prototype chain.
// Reducer function
function rootReducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    // Other cases for different actions...
    default:
      return state;
  }
}
This code snippet is an example of a reducer function that handles various actions. It takes the current state and an action, and returns a new state based on the action type.
// Store usage
const store = createStore(rootReducer);

store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // Should log the current state

store.resetState(); // Resets the state to an object without a prototype
console.log(store.getState()); // Should log an empty object without a prototype
This code snippet demonstrates how to use the Redux-like store created earlier. It dispatches an 'INCREMENT' action to change the state, logs the current state, and then calls `resetState` to reset the state to an empty object without a prototype, and logs the state again.