Gabriel Richards
Gabriel Richards

Reputation: 73

In NextJS 14, Changed Cookie State Not Sent to Server Upon router.refresh()

Summary

Cookie data is used in a server component to modify a fetch call.

Cooke state is modified in a client component (using js-cookie).

router.refresh() is called in the client component after the cookie state is modified.

The modified cookie state is not sent to the server in the request header.

The prior cookie state is sent instead.

Expected Behavior

The current state of the browser cookie should be sent with router.refresh()

Abbreviated Example Code

In a context provider:

export function SelectedVehicleContextProvider({ children }: { children: ReactNode }) {
/*...*/

  // If a new vehicle is selected, persist it to cookie
  useEffect(() => {
    if (selectedVehicle) {
      const selectedVehicleString = JSON.stringify(selectedVehicle)
      Cookies.set('selectedVehicle', selectedVehicleString, { expires: 365 })
    } else {
      Cookies.remove('selectedVehicle')
    }
  }, [selectedVehicle])

/*...*/
}

In a client component using the context provider:

export default function VehicleSelector({ onVehicleSelect }: { onVehicleSelect?: () => void }) {
/*...*/

      setSelectedVehicle(selectedVehicleData)

      router.refresh()


/*...*/
}

With that code, after router.refresh() executes, you will see an RSC request to the server and if you inspect the Request headers, you will see that the cookies value is from the previous state.

Upvotes: 0

Views: 207

Answers (1)

Gabriel Richards
Gabriel Richards

Reputation: 73

I'm not really sure if this is a proper solution or not, but I discovered that adding:

router.push(currentPathname)

before

router.refresh()

caused the newly updated cookie state to be sent to the server.

Upvotes: 0

Related Questions