Here is the simple thing. React routing redirect path depends on the value in cookies, so how do I handle it Server Side?
render() {
  something = cookie.get('my-something-value') || 'default '; // always takes defualt value beacuse cookies are not available 
  return (
    <Switch>
      <Route />
      <Route />
      <Redirect to={`/something/${val}`}/>
    </Switch>
  )
}
So renderToString method in the server parses elements to string ignoring this condition and I get wrong redirect even though I have cookies set
I had faced similar kind of issue. It was resolved by:
My renderToString on server side looked somewhat like this:
renderToString(
  <Provider store={store}>
    <StaticRouter ...>
      <MyRoutes ... serverCookie={req.headers.cookie} />
    </StaticRouter>
  </Provider>
)
MyRoutes file looked like:
render(){
  const cookie = isServerSide
    ? this.props.serverCookie
    : cookie.get('my-something-value')
  const path = cookie ? "/pathC" : "/pathD"
  return (
    <Switch>
        <Route
          path="/pathA"
          component={ComponentA}
        />
        <Route
          path="/pathB"
          component={ComponentA}
        />
        <Redirect to={path} />
      ...
    </Switch>
  )
}
Note: You will need to parse your cookies properly using some cookie-parser before using.
Hope it helps and solves your issue. Revert for any doubts/clarifications.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With