🛠 iron-session examples: Pages Router

+ API routes, redirects, and fetch

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


How it works
  1. The form is submitted to /api/pages-router-redirect-api-route-fetch/session (API route) via a POST call (non-fetch). The API route sets the session data and redirects back to /pages-router-redirect-api-route-fetch (this page).
  2. The page gets the session data via a fetch call to /api/pages-router-redirect-api-route-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 /api/pages-router-redirect-api-route-fetch/session?action=logout which destroy the session and redirects back to /pages-router-redirect-api-route-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