Skip to content

Commit

Permalink
fix: Avoid redundant Set-Cookie headers in server responses
Browse files Browse the repository at this point in the history
Previously, a response from `getServerSideProps` or `getInitialProps` would always include Set-Cookie headers identical to the existing state cookies.
  • Loading branch information
bjoluc committed Aug 18, 2022
1 parent 2257185 commit 8b48978
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions main/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,22 @@ export const nextReduxCookieMiddleware: (config: NextReduxCookieMiddlewareConfig
const result = next(action);
const newState = store.getState() as JsonObject;

const isServerSideHydrateAction = !isClient() && action.type === HYDRATE;

// If cookies are available (which is not the case during `getStaticProps()`), write the
// new state into cookies wherever necessary
// new state into cookies wherever it differs from the old state
if (cookies) {
walkState(
subtrees,
({cookieName, defaultState}, oldSubtreeState, newSubtreeState) => {
if (!isEqual(oldSubtreeState, newSubtreeState)) {
// When handling the HYDRATE action on the server, old subtree state (initial state)
// is irrelevant for updating cookies. In this case, we have to consider the cookie
// state instead:
const originState = isServerSideHydrateAction
? (cookies.getAll()[cookieName] as unknown)
: oldSubtreeState;

if (!isEqual(originState, newSubtreeState)) {
// Subtree state has changed
if (
typeof defaultState !== "undefined" &&
Expand Down

0 comments on commit 8b48978

Please sign in to comment.