I'm developing user session management for a website. Flow:
- Session is nonexistent/invalid, frontend directs user to login page
- User logs in
- Backend creates session in its database
- Backend creates session ID cookie
- Frontend passes session ID cookie in each request for authentication
My question: how will frontend know whether session is nonexistent/invalid? Needs to handle the case when a user changes their password, then all their sessions across devices are revoked. So frontend needs to check backend somehow.
Possible approaches:
Backend provides a GET /session API, which tells whether session is active. Frontend calls it before each request, and redirects to login if session is inactive. But this seems like a lot of extra requests.
Frontend calls GET /session upon each browser load of website (CTRL-R). If session is invalidated while on an authed page, the page won't work until reloaded, which will go to login. This might be enough, if unauthed and authed pages are completely separate.
Backend APIs return HTTP 401 if session is inactive. When frontend sees that, it directs user to login. This is more realtime than #2 and doesn't need the extra GET /session requests. I don't know if this has any issues I'm not seeing.
Which is the best approach?