A have a React app that handles the login form and a separate React app that shows a dashboard. I want the browser to load the dashboard app when the login is successful.
I've attempted to do this by sending a redirect response from my server (status code: 302, Location header attached). The server responds to this request correctly and sends the index.html
file of the dashboard app to the client.
The browser receives this file successfully, but does not load it (URL does not change either).
Here're the response headers to the received index.html
file:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 624
Content-Type: text/html; charset=utf-8
Last-Modified: Sun, 16 Oct 2022 09:40:25 GMT
Date: Sun, 16 Oct 2022 16:38:37 GMT
My question is: how can I make the browser replace all currently used React code with the one that's coming from redirect? Do I need to set additional headers for that? Or should this be handled in frontend somehow?
CodePudding user response:
I managed to implement it by doing these three things:
In the login app, once I receive a response with the dashboard
index.html
file, I reset URL to the root path withwindow.location.href = "http://localhost:3001/"
. This automatically loads this newly receivedindex.html
file.On my server, I make sure to check if the request contains the correct cookie. If it does, I return the dashboard app files. Otherwise, I return the login app files.
Whenever the browser sends a request for some internal React path (e.g.
localhost:3001/article/1
), I return the correctindex.html
file instead. Once theindex.html
is loaded, the app will automatically open the right page (I'm using react-router here).This takes care of the situations when I want to open a link to a specific route within my React app.
Once login is successful and I get redirected to the dashboard app, if I click on the back button, the browser opens the previously replaced login app again. This happens because all responses from the server are cashed automatically.
To avoid this, I set the
Cache-Control
header tono-store
for my responses on the server. This way, I can click on the back button and get redirected to the root dashboard page instead (or some other path that is handled by the dashboard app).The
no-cache
header is only required when the login app is served. The dashboard app can be cached. I'm not sure how this will change when I'll implement the logout functionality.
This pretty much allows for the seamless transition between the two React apps I'm serving. The no-cache
condition seems a bit harsh, but at this moment I don't see any way around it.