I have been building a React Application, using redux for state management. After looking at tutorials online, I was able build a nice app which had login/logout functionality. But on refresh, I got a 404. I realized that it is client-side rendering. So, I added an express server which handles the routes, doing server side rendering.
The api I call for data fetch requires authentication. I call the api with the jwt token in componentDidMount. It works fine on the client side.
Here is my question:
But if the user refreshes the page, the server sends the html skeleton, followed by client making the call in componentDidMount. Can the data fetch be done on the server side? If yes, how would I get the token(from browsers' localStorage)?
You cannot get data from the browsers localStorage
, because the server has no access to the browser. If you API needs an access token, then you must first render the page, get the token from localStorage
and only then fetch the data form the API.