🛠 iron-session examples: App router

+ client components, route handlers, redirects, and fetch

How to test: Login and refresh the page to see iron-session in action.


GitHub Logo Get the code for this example
How it works
  1. The form is submitted to /app-router-client-component-redirect-route-handler-fetch/session (API route) via a POST call (non-fetch). The API route sets the session data and redirects back to /app-router-client-component-redirect-route-handler-fetch (this page).
  2. The page gets the session data via a fetch call to /app-router-client-component-redirect-route-handler-fetch/session (API route). The API route either return the session data (logged in) or a default session (not logged in).
  3. The logout is a regular link navigating to /app-router-client-component-redirect-route-handler-fetch/logout which destroy the session and redirects back to /app-router-client-component-redirect-route-handler-fetch (this page).

Pros: Straightforward. It does not rely on too many APIs. This is what we would have implemented a few years ago and is good enough for many websites.

Cons: No synchronization. The session is not updated between tabs and windows. If you login or logout in one window or tab, the others are still showing the previous state. Also, we rely on full page navigation and redirects for login and logout. We could remove them by using fetch instead.

← All examples