workos / authkit-nextjs

The WorkOS library for Next.js provides convenient helpers for authentication and session management using WorkOS & AuthKit with Next.js.
MIT License
67 stars 18 forks source link

Check for valid session when tab becomes active #75

Closed lucasmotta closed 2 months ago

lucasmotta commented 3 months ago

Description

Add a new Provider component that users should wrap their application in order to check for invalid sessions, in case for example, a tab stayed open for too long or the user signed out in a different tab.

If the user has a invalid session upon returning to a tab, the page will be reloaded so the middleware can take care of the redirection.

By forcing this page reload, we prevent possible CORS issues as server actions would throw an error as you are not authenticated.

The current use of the Provider is to listen to tab events and check for invalid session, but we can eventually introduce new feature inside the Provider, like passing down the current user in a context so it can be accessed in client components.

How does that work?

When the user switches back to the app, we make a call to a server action, which in Next.js world is just a POST request to the current route the user is in.

If the user has a valid session, the request will most likely be successful so we don't need to do anything. But if the user does not have an active session, there are two outcomes:

And also, if the user does not have the middlewareAuth enabled, the server action will also be successful, so we don't reload the page.

Open questions