Docs

Handling Session Expiration

How to detect session expiration, for example to show a login view to the user.

You can use the built-in middleware InvalidSessionMiddleWare to detect when a user session expires.

This middleware requires a function as a constructor parameter (type of OnInvalidSessionCallback). The function should return a promise of LoginResult, containing the metadata of a login result, including:

error

Indicates whether the login attempt has failed.

token

In the event of a successful login, this is the cross-site request forgery (CSRF) prevention token, which can be extracted from the index.html page. See CSRF protection of Hilla endpoints for more information.

errorTitle

A short text describing a login error.

errorMessage

A more detailed explanation of the login error.

Example

As an example, you can use the InvalidSessionMiddleware to show a login view to the user.

Configure the ConnectClient with the middleware, and let the callback open a login overlay:

Source code
frontend/connect-client.ts

The overlay reuses the login function from the useAuth hook, and resolves the promise the middleware is waiting on once the user has signed in again:

Source code
frontend/auth/SessionExpiredLoginOverlay.tsx

Render SessionExpiredLoginOverlay once in your main layout, so that it’s mounted for every view. It stays closed until the middleware reports an expired session, and the endpoint call that triggered it proceeds after a successful login.

Updated –