I have a private HttpOnly cookie that is encrypted with the user's id (this is used for authentication).
I also have a GET request route (let's call it GET X
) that is ran when the page loads. But I only want it to run if the user is logged in.
It seems like there are two options, both of which are suboptimal.
Option 1) Run the route regardless when the site loads. If the user is not logged in then the route will 404 because the cookie will not be sent. This is fine, but it incurs the cost of a pointless request and shows up as a red 404 in the console.
Option 2) Do a GET request to the server first to check if the user is logged in. The server returns true or false by decoding the cookie and seeing if it is valid. When the client receives a response, if they're not logged in, then they just don't perform the GET X
request. And if they are logged in then they don't.
The problem with Option 1 is that if the user is not logged in then GET X
is sent pointlessly since it will just 404.
The problem with Option 2 is that there is added latency. That is, before GET X
can be executed, we have to wait for the round trip from the server.
Is there an alternative solution? Ideally it would be possible to check for the existence of the HttpOnly cookie, and then if it didn't exist, to not send the request. But as far as I can tell it is not possible to do this. I'd like to avoid the roundtrip latency with Option 2, but also avoid the pointless 404's with Option 1. Is there a solution to this?