@netlify/identity 0.3.0-alpha.0 → 0.3.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,13 +4,38 @@ A lightweight, no-config headless authentication library for projects using Netl
4
4
 
5
5
  > **Status:** Beta. The API may change before 1.0.
6
6
 
7
- For a pre-built login widget, see [netlify-identity-widget](https://github.com/netlify/netlify-identity-widget).
8
-
9
7
  **Prerequisites:**
10
8
 
11
9
  - [Netlify Identity](https://docs.netlify.com/security/secure-access-to-sites/identity/) must be enabled on your Netlify project
12
10
  - For local development, use [`netlify dev`](https://docs.netlify.com/cli/local-development/) so the Identity endpoint is available
13
11
 
12
+ ### How this library relates to other Netlify auth packages
13
+
14
+ | Package | What it is | When to use it |
15
+ | ------------------------------------------------------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
16
+ | **`@netlify/identity`** (this library) | Headless TypeScript API for browser and server | You want full control over your auth UI and need server-side auth (SSR, Netlify Functions) |
17
+ | [`netlify-identity-widget`](https://github.com/netlify/netlify-identity-widget) | Pre-built login/signup modal (HTML + CSS) | You want a drop-in UI component with no custom design |
18
+ | [`gotrue-js`](https://github.com/netlify/gotrue-js) | Low-level GoTrue HTTP client (browser only) | You're building your own auth wrapper and need direct API access |
19
+
20
+ This library wraps `gotrue-js` in the browser and calls the GoTrue HTTP API directly on the server. It provides a unified API that works in both contexts, handles cookie management, and normalizes the user object. You do not need to install `gotrue-js` or the widget separately.
21
+
22
+ ## Table of contents
23
+
24
+ - [Installation](#installation)
25
+ - [Quick start](#quick-start)
26
+ - [API](#api)
27
+ - [Functions](#functions) -- `getUser`, `login`, `signup`, `logout`, `oauthLogin`, `handleAuthCallback`, `onAuthChange`, `hydrateSession`, and more
28
+ - [Types](#types) -- `User`, `AuthEvent`, `CallbackResult`, `Settings`, etc.
29
+ - [Errors](#errors) -- `AuthError`, `MissingIdentityError`
30
+ - [Framework integration](#framework-integration) -- Next.js, Remix, TanStack Start, Astro, SvelteKit
31
+ - [Guides](#guides)
32
+ - [React `useAuth` hook](#react-useauth-hook)
33
+ - [Listening for auth changes](#listening-for-auth-changes)
34
+ - [OAuth login](#oauth-login)
35
+ - [Password recovery](#password-recovery)
36
+ - [Invite acceptance](#invite-acceptance)
37
+ - [Session lifetime](#session-lifetime)
38
+
14
39
  ## Installation
15
40
 
16
41
  ```bash
@@ -19,18 +44,20 @@ npm install @netlify/identity
19
44
 
20
45
  ## Quick start
21
46
 
22
- ### Browser
47
+ ### Log in (browser)
23
48
 
24
49
  ```ts
25
- import { getUser } from '@netlify/identity'
50
+ import { login, getUser } from '@netlify/identity'
26
51
 
27
- const user = getUser()
28
- if (user) {
29
- console.log(`Hello, ${user.name}`)
30
- }
52
+ // Log in
53
+ const user = await login('jane@example.com', 'password123')
54
+ console.log(`Hello, ${user.name}`)
55
+
56
+ // Later, check auth state synchronously
57
+ const currentUser = getUser()
31
58
  ```
32
59
 
33
- ### Netlify Function
60
+ ### Protect a Netlify Function
34
61
 
35
62
  ```ts
36
63
  import { getUser } from '@netlify/identity'
@@ -43,7 +70,7 @@ export default async (req: Request, context: Context) => {
43
70
  }
44
71
  ```
45
72
 
46
- ### Edge Function
73
+ ### Protect an Edge Function
47
74
 
48
75
  ```ts
49
76
  import { getUser } from '@netlify/identity'
@@ -66,7 +93,9 @@ export default async (req: Request, context: Context) => {
66
93
  getUser(): User | null
67
94
  ```
68
95
 
69
- Returns the current authenticated user, or `null` if not logged in. Synchronous, never throws.
96
+ Returns the current authenticated user, or `null` if not logged in. Synchronous. Never throws.
97
+
98
+ > **Next.js note:** Calling `getUser()` in a Server Component opts the page into [dynamic rendering](https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-rendering) because it reads cookies. This is expected and correct for authenticated pages. Next.js handles the internal dynamic rendering signal automatically.
70
99
 
71
100
  #### `isAuthenticated`
72
101
 
@@ -109,12 +138,14 @@ In the browser, uses gotrue-js and emits a `'login'` event. On the server (Netli
109
138
  #### `signup`
110
139
 
111
140
  ```ts
112
- signup(email: string, password: string, data?: Record<string, unknown>): Promise<User>
141
+ signup(email: string, password: string, data?: SignupData): Promise<User>
113
142
  ```
114
143
 
115
144
  Creates a new account. Works in both browser and server contexts.
116
145
 
117
- In the browser, uses gotrue-js and emits `'login'` if autoconfirm is enabled. On the server, calls the GoTrue HTTP API directly and sets the `nf_jwt` cookie if the user is auto-confirmed.
146
+ If autoconfirm is enabled in your Identity settings, the user is logged in immediately: cookies are set and a `'login'` event is emitted. If autoconfirm is **disabled** (the default), the user receives a confirmation email and must click the link before they can log in. In that case, no cookies are set and no auth event is emitted.
147
+
148
+ The optional `data` parameter sets user metadata (e.g., `{ full_name: 'Jane Doe' }`), stored in the user's `user_metadata` field.
118
149
 
119
150
  **Throws:** `AuthError` on failure (e.g., email already registered, signup disabled). In the browser, `MissingIdentityError` if Identity is not configured. On the server, `AuthError` if the Netlify Functions runtime is not available.
120
151
 
@@ -126,9 +157,9 @@ logout(): Promise<void>
126
157
 
127
158
  Logs out the current user and clears the session. Works in both browser and server contexts.
128
159
 
129
- In the browser, uses gotrue-js and emits a `'logout'` event. On the server, calls GoTrue's `/logout` endpoint with the JWT from the `nf_jwt` cookie, then deletes the cookie.
160
+ In the browser, uses gotrue-js and emits a `'logout'` event. On the server, calls GoTrue's `/logout` endpoint with the JWT from the `nf_jwt` cookie, then deletes the cookie. Auth cookies are always cleared, even if the GoTrue call fails.
130
161
 
131
- **Throws:** `AuthError` on network failure. In the browser, `MissingIdentityError` if Identity is not configured. On the server, `AuthError` if the Netlify Functions runtime is not available.
162
+ **Throws:** In the browser, `MissingIdentityError` if Identity is not configured. On the server, `AuthError` if the Netlify Functions runtime is not available.
132
163
 
133
164
  #### `oauthLogin`
134
165
 
@@ -140,7 +171,7 @@ Redirects to an OAuth provider. The page navigates away, so this function never
140
171
 
141
172
  The `provider` argument should be one of the `AuthProvider` values: `'google'`, `'github'`, `'gitlab'`, `'bitbucket'`, `'facebook'`, or `'saml'`.
142
173
 
143
- **Throws:** `MissingIdentityError` if Identity is not configured. `Error` if called on the server.
174
+ **Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if called on the server.
144
175
 
145
176
  #### `handleAuthCallback`
146
177
 
@@ -158,7 +189,29 @@ Processes the URL hash after an OAuth redirect, email confirmation, password rec
158
189
  onAuthChange(callback: AuthCallback): () => void
159
190
  ```
160
191
 
161
- Subscribes to auth state changes (login, logout, token refresh, user updates). Returns an unsubscribe function. Also fires on cross-tab session changes. No-op on the server.
192
+ Subscribes to auth state changes (login, logout, token refresh, user updates, and recovery). Returns an unsubscribe function. Also fires on cross-tab session changes. No-op on the server. The `'recovery'` event fires when `handleAuthCallback()` processes a password recovery token; listen for it to redirect users to a password reset form.
193
+
194
+ #### `hydrateSession`
195
+
196
+ ```ts
197
+ hydrateSession(): Promise<User | null>
198
+ ```
199
+
200
+ Bootstraps the browser-side gotrue-js session from server-set auth cookies (`nf_jwt`, `nf_refresh`). Returns the hydrated `User`, or `null` if no auth cookies are present. No-op on the server.
201
+
202
+ **When to use:** After a server-side login (e.g., via a Netlify Function or Server Action), the `nf_jwt` cookie is set but gotrue-js has no browser session yet. `getUser()` works immediately (it decodes the cookie), but account operations like `updateUser()` or `verifyEmailChange()` require a live gotrue-js session. Call `hydrateSession()` once on page load to bridge this gap.
203
+
204
+ If a gotrue-js session already exists (e.g., from a browser-side login), this is a no-op and returns the existing user.
205
+
206
+ ```ts
207
+ import { hydrateSession, updateUser } from '@netlify/identity'
208
+
209
+ // On page load, hydrate the session from server-set cookies
210
+ await hydrateSession()
211
+
212
+ // Now browser account operations work
213
+ await updateUser({ data: { full_name: 'Jane Doe' } })
214
+ ```
162
215
 
163
216
  #### `requestPasswordRecovery`
164
217
 
@@ -213,10 +266,10 @@ Redeems a recovery token and sets a new password. Logs the user in on success.
213
266
  #### `updateUser`
214
267
 
215
268
  ```ts
216
- updateUser(updates: Record<string, unknown>): Promise<User>
269
+ updateUser(updates: UserUpdates): Promise<User>
217
270
  ```
218
271
 
219
- Updates the current user's metadata or credentials. Requires an active session.
272
+ Updates the current user's metadata or credentials. Requires an active session. Pass `email` or `password` to change credentials, or `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
220
273
 
221
274
  **Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if no user is logged in, or the update fails.
222
275
 
@@ -325,6 +378,27 @@ interface IdentityConfig {
325
378
  type AuthProvider = 'google' | 'github' | 'gitlab' | 'bitbucket' | 'facebook' | 'saml' | 'email'
326
379
  ```
327
380
 
381
+ #### `UserUpdates`
382
+
383
+ ```ts
384
+ interface UserUpdates {
385
+ email?: string
386
+ password?: string
387
+ data?: Record<string, unknown>
388
+ [key: string]: unknown
389
+ }
390
+ ```
391
+
392
+ Fields accepted by `updateUser()`. All fields are optional.
393
+
394
+ #### `SignupData`
395
+
396
+ ```ts
397
+ type SignupData = Record<string, unknown>
398
+ ```
399
+
400
+ User metadata passed as the third argument to `signup()`. Stored in the user's `user_metadata` field.
401
+
328
402
  #### `AppMetadata`
329
403
 
330
404
  ```ts
@@ -335,10 +409,24 @@ interface AppMetadata {
335
409
  }
336
410
  ```
337
411
 
412
+ #### `AUTH_EVENTS`
413
+
414
+ ```ts
415
+ const AUTH_EVENTS: {
416
+ LOGIN: 'login'
417
+ LOGOUT: 'logout'
418
+ TOKEN_REFRESH: 'token_refresh'
419
+ USER_UPDATED: 'user_updated'
420
+ RECOVERY: 'recovery'
421
+ }
422
+ ```
423
+
424
+ Constants for auth event names. Use these instead of string literals for type safety and autocomplete.
425
+
338
426
  #### `AuthEvent`
339
427
 
340
428
  ```ts
341
- type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated'
429
+ type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated' | 'recovery'
342
430
  ```
343
431
 
344
432
  #### `AuthCallback`
@@ -380,29 +468,367 @@ class MissingIdentityError extends Error {}
380
468
 
381
469
  Thrown when Identity is not configured in the current environment.
382
470
 
471
+ ## Framework integration
472
+
473
+ ### Recommended pattern for SSR frameworks
474
+
475
+ For SSR frameworks (Next.js, Remix, Astro, TanStack Start), the recommended pattern is:
476
+
477
+ - **Browser-side** for auth mutations: `login()`, `signup()`, `logout()`, `oauthLogin()`
478
+ - **Server-side** for reading auth state: `getUser()`, `getSettings()`, `getIdentityConfig()`
479
+
480
+ Browser-side auth mutations call the GoTrue API directly from the browser, set the `nf_jwt` cookie and gotrue-js localStorage, and emit `onAuthChange` events. This keeps the client UI in sync immediately. Server-side reads work because the cookie is sent with every request.
481
+
482
+ The library also supports server-side mutations (`login()`, `signup()`, `logout()` inside Netlify Functions), but these require the Netlify Functions runtime to set cookies. After a server-side mutation, you need a full page navigation so the browser sends the new cookie.
483
+
484
+ ### Next.js (App Router)
485
+
486
+ **Server Actions return results; the client handles navigation:**
487
+
488
+ ```tsx
489
+ // app/actions.ts
490
+ 'use server'
491
+ import { login, logout } from '@netlify/identity'
492
+
493
+ export async function loginAction(formData: FormData) {
494
+ const email = formData.get('email') as string
495
+ const password = formData.get('password') as string
496
+ await login(email, password)
497
+ return { success: true }
498
+ }
499
+
500
+ export async function logoutAction() {
501
+ await logout()
502
+ return { success: true }
503
+ }
504
+ ```
505
+
506
+ ```tsx
507
+ // app/login/page.tsx
508
+ 'use client'
509
+ import { loginAction } from '../actions'
510
+
511
+ export default function LoginPage() {
512
+ async function handleSubmit(formData: FormData) {
513
+ const result = await loginAction(formData)
514
+ if (result.success) {
515
+ window.location.href = '/dashboard' // full page load
516
+ }
517
+ }
518
+
519
+ return <form action={handleSubmit}>...</form>
520
+ }
521
+ ```
522
+
523
+ ```tsx
524
+ // app/dashboard/page.tsx
525
+ import { getUser } from '@netlify/identity'
526
+ import { redirect } from 'next/navigation'
527
+
528
+ export default function Dashboard() {
529
+ const user = getUser()
530
+ if (!user) redirect('/login')
531
+
532
+ return <h1>Hello, {user.email}</h1>
533
+ }
534
+ ```
535
+
536
+ Use `window.location.href` instead of Next.js `redirect()` after server-side auth mutations. Next.js `redirect()` triggers a soft navigation via the Router, which may not include the newly-set auth cookie. A full page load ensures the cookie is sent and the server sees the updated auth state. Reading auth state with `getUser()` in Server Components works normally, and `redirect()` is fine for auth gates (where no cookie was just set).
537
+
538
+ ### Remix
539
+
540
+ **Login with Action (server-side pattern):**
541
+
542
+ ```tsx
543
+ // app/routes/login.tsx
544
+ import { login } from '@netlify/identity'
545
+ import { redirect, json } from '@remix-run/node'
546
+ import type { ActionFunctionArgs } from '@remix-run/node'
547
+
548
+ export async function action({ request }: ActionFunctionArgs) {
549
+ const formData = await request.formData()
550
+ const email = formData.get('email') as string
551
+ const password = formData.get('password') as string
552
+
553
+ try {
554
+ await login(email, password)
555
+ return redirect('/dashboard')
556
+ } catch (error) {
557
+ return json({ error: (error as Error).message }, { status: 400 })
558
+ }
559
+ }
560
+ ```
561
+
562
+ ```tsx
563
+ // app/routes/dashboard.tsx
564
+ import { getUser } from '@netlify/identity'
565
+ import { redirect } from '@remix-run/node'
566
+
567
+ export async function loader() {
568
+ const user = getUser()
569
+ if (!user) return redirect('/login')
570
+ return { user }
571
+ }
572
+ ```
573
+
574
+ Remix `redirect()` works after server-side `login()` because Remix actions return real HTTP responses. The browser receives a 302 with the `Set-Cookie` header already applied, so the next request includes the auth cookie. This is different from Next.js, where `redirect()` in a Server Action triggers a client-side (soft) navigation that may not include newly-set cookies.
575
+
576
+ ### TanStack Start
577
+
578
+ **Login from the browser (recommended):**
579
+
580
+ ```tsx
581
+ // app/server/auth.ts - server functions for reads only
582
+ import { createServerFn } from '@tanstack/react-start'
583
+ import { getUser } from '@netlify/identity'
584
+
585
+ export const getServerUser = createServerFn({ method: 'GET' }).handler(async () => {
586
+ const user = getUser()
587
+ return user ?? null
588
+ })
589
+ ```
590
+
591
+ ```tsx
592
+ // app/routes/login.tsx - browser-side auth for mutations
593
+ import { login, signup, onAuthChange } from '@netlify/identity'
594
+ import { getServerUser } from '~/server/auth'
595
+
596
+ export const Route = createFileRoute('/login')({
597
+ beforeLoad: async () => {
598
+ const user = await getServerUser()
599
+ if (user) throw redirect({ to: '/dashboard' })
600
+ },
601
+ component: Login,
602
+ })
603
+
604
+ function Login() {
605
+ const handleLogin = async (email: string, password: string) => {
606
+ await login(email, password) // browser-side: sets cookie + localStorage
607
+ window.location.href = '/dashboard'
608
+ }
609
+ // ...
610
+ }
611
+ ```
612
+
613
+ ```tsx
614
+ // app/routes/dashboard.tsx
615
+ import { logout } from '@netlify/identity'
616
+ import { getServerUser } from '~/server/auth'
617
+
618
+ export const Route = createFileRoute('/dashboard')({
619
+ beforeLoad: async () => {
620
+ const user = await getServerUser()
621
+ if (!user) throw redirect({ to: '/login' })
622
+ },
623
+ loader: async () => {
624
+ const user = await getServerUser()
625
+ return { user: user! }
626
+ },
627
+ component: Dashboard,
628
+ })
629
+
630
+ function Dashboard() {
631
+ const { user } = Route.useLoaderData()
632
+
633
+ const handleLogout = async () => {
634
+ await logout() // browser-side: clears cookie + localStorage
635
+ window.location.href = '/'
636
+ }
637
+ // ...
638
+ }
639
+ ```
640
+
641
+ Use `window.location.href` instead of TanStack Router's `navigate()` after auth changes. This ensures the browser sends the updated cookie on the next request.
642
+
643
+ ### Astro (SSR)
644
+
645
+ **Login via API endpoint (server-side pattern):**
646
+
647
+ ```ts
648
+ // src/pages/api/login.ts
649
+ import type { APIRoute } from 'astro'
650
+ import { login } from '@netlify/identity'
651
+
652
+ export const POST: APIRoute = async ({ request }) => {
653
+ const { email, password } = await request.json()
654
+
655
+ try {
656
+ await login(email, password)
657
+ return new Response(null, {
658
+ status: 302,
659
+ headers: { Location: '/dashboard' },
660
+ })
661
+ } catch (error) {
662
+ return Response.json({ error: (error as Error).message }, { status: 400 })
663
+ }
664
+ }
665
+ ```
666
+
667
+ ```astro
668
+ ---
669
+ // src/pages/dashboard.astro
670
+ import { getUser } from '@netlify/identity'
671
+
672
+ const user = getUser()
673
+ if (!user) return Astro.redirect('/login')
674
+ ---
675
+ <h1>Hello, {user.email}</h1>
676
+ ```
677
+
678
+ ### SvelteKit
679
+
680
+ **Login from the browser (recommended):**
681
+
682
+ ```svelte
683
+ <!-- src/routes/login/+page.svelte -->
684
+ <script lang="ts">
685
+ import { login } from '@netlify/identity'
686
+
687
+ let email = ''
688
+ let password = ''
689
+ let error = ''
690
+
691
+ async function handleLogin() {
692
+ try {
693
+ await login(email, password)
694
+ window.location.href = '/dashboard'
695
+ } catch (e) {
696
+ error = (e as Error).message
697
+ }
698
+ }
699
+ </script>
700
+
701
+ <form on:submit|preventDefault={handleLogin}>
702
+ <input bind:value={email} type="email" />
703
+ <input bind:value={password} type="password" />
704
+ <button type="submit">Log in</button>
705
+ {#if error}<p>{error}</p>{/if}
706
+ </form>
707
+ ```
708
+
709
+ ```ts
710
+ // src/routes/dashboard/+page.server.ts
711
+ import { getUser } from '@netlify/identity'
712
+ import { redirect } from '@sveltejs/kit'
713
+
714
+ export function load() {
715
+ const user = getUser()
716
+ if (!user) redirect(302, '/login')
717
+ return { user }
718
+ }
719
+ ```
720
+
721
+ ### Handling OAuth callbacks in SPAs
722
+
723
+ All SPA frameworks need a callback handler that runs on page load to process OAuth redirects, email confirmations, and password recovery tokens. Use a **wrapper component** that blocks page content while processing tokens. This prevents a flash of unauthenticated content that occurs when the page renders before the callback completes.
724
+
725
+ ```tsx
726
+ // React component (works with Next.js, Remix, TanStack Start)
727
+ import { useEffect, useState } from 'react'
728
+ import { handleAuthCallback } from '@netlify/identity'
729
+
730
+ const AUTH_HASH_PATTERN = /^#(confirmation_token|recovery_token|invite_token|email_change_token|access_token)=/
731
+
732
+ export function CallbackHandler({ children }: { children: React.ReactNode }) {
733
+ const [processing, setProcessing] = useState(
734
+ () => typeof window !== 'undefined' && AUTH_HASH_PATTERN.test(window.location.hash),
735
+ )
736
+ const [error, setError] = useState<string | null>(null)
737
+
738
+ useEffect(() => {
739
+ if (!window.location.hash || !AUTH_HASH_PATTERN.test(window.location.hash)) return
740
+
741
+ handleAuthCallback()
742
+ .then((result) => {
743
+ if (!result) {
744
+ setProcessing(false)
745
+ return
746
+ }
747
+ if (result.type === 'invite') {
748
+ window.location.href = `/accept-invite?token=${result.token}`
749
+ } else if (result.type === 'recovery') {
750
+ window.location.href = '/reset-password'
751
+ } else {
752
+ window.location.href = '/dashboard'
753
+ }
754
+ })
755
+ .catch((err) => {
756
+ setError(err instanceof Error ? err.message : 'Callback failed')
757
+ setProcessing(false)
758
+ })
759
+ }, [])
760
+
761
+ if (error) return <div>Auth error: {error}</div>
762
+ if (processing) return <div>Confirming your account...</div>
763
+ return <>{children}</>
764
+ }
765
+ ```
766
+
767
+ Wrap your page content with this component in your **root layout** so it runs on every page:
768
+
769
+ ```tsx
770
+ // Root layout
771
+ <CallbackHandler>
772
+ <Outlet /> {/* or {children} in Next.js */}
773
+ </CallbackHandler>
774
+ ```
775
+
776
+ If you only mount it on a `/callback` route, OAuth redirects and email confirmation links that land on other pages will not be processed.
777
+
383
778
  ## Guides
384
779
 
780
+ ### React `useAuth` hook
781
+
782
+ The library is framework-agnostic, but here's a simple React hook for keeping components in sync with auth state:
783
+
784
+ ```tsx
785
+ import { useState, useEffect } from 'react'
786
+ import { getUser, onAuthChange } from '@netlify/identity'
787
+ import type { User } from '@netlify/identity'
788
+
789
+ export function useAuth() {
790
+ const [user, setUser] = useState<User | null>(getUser())
791
+
792
+ useEffect(() => {
793
+ return onAuthChange((_event, user) => setUser(user))
794
+ }, [])
795
+
796
+ return user
797
+ }
798
+ ```
799
+
800
+ ```tsx
801
+ function NavBar() {
802
+ const user = useAuth()
803
+ return user ? <p>Hello, {user.name}</p> : <a href="/login">Log in</a>
804
+ }
805
+ ```
806
+
385
807
  ### Listening for auth changes
386
808
 
387
- Use `onAuthChange` to keep your UI in sync with auth state. It fires on login, logout, token refresh, and user updates. It also detects session changes in other browser tabs (via `localStorage`).
809
+ Use `onAuthChange` to keep your UI in sync with auth state. It fires on login, logout, token refresh, user updates, and recovery. It also detects session changes in other browser tabs (via `localStorage`).
388
810
 
389
811
  ```ts
390
- import { onAuthChange } from '@netlify/identity'
812
+ import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
391
813
 
392
814
  const unsubscribe = onAuthChange((event, user) => {
393
815
  switch (event) {
394
- case 'login':
816
+ case AUTH_EVENTS.LOGIN:
395
817
  console.log('Logged in:', user?.email)
396
818
  break
397
- case 'logout':
819
+ case AUTH_EVENTS.LOGOUT:
398
820
  console.log('Logged out')
399
821
  break
400
- case 'token_refresh':
822
+ case AUTH_EVENTS.TOKEN_REFRESH:
401
823
  console.log('Token refreshed for:', user?.email)
402
824
  break
403
- case 'user_updated':
825
+ case AUTH_EVENTS.USER_UPDATED:
404
826
  console.log('User updated:', user?.email)
405
827
  break
828
+ case AUTH_EVENTS.RECOVERY:
829
+ console.log('Recovery login:', user?.email)
830
+ // Redirect to password reset form, then call updateUser({ password })
831
+ break
406
832
  }
407
833
  })
408
834
 
@@ -435,11 +861,11 @@ if (result?.type === 'oauth') {
435
861
  }
436
862
  ```
437
863
 
438
- `handleAuthCallback()` exchanges the token in the URL hash, logs the user in, clears the hash, and emits a `'login'` event via `onAuthChange`.
864
+ `handleAuthCallback()` exchanges the token in the URL hash, logs the user in, clears the hash, and emits an auth event via `onAuthChange` (`'login'` for OAuth/confirmation, `'recovery'` for password recovery).
439
865
 
440
866
  ### Password recovery
441
867
 
442
- Password recovery is a two-step flow. The library handles the token exchange automatically via `handleAuthCallback()`, which logs the user in and returns `{type: 'recovery', user}`. You then show a "set new password" form and call `updateUser()` to save it.
868
+ Password recovery is a two-step flow. The library handles the token exchange automatically via `handleAuthCallback()`, which logs the user in and returns `{type: 'recovery', user}`. A `'recovery'` event (not `'login'`) is emitted via `onAuthChange`, so event-based listeners can also detect this flow. You then show a "set new password" form and call `updateUser()` to save it.
443
869
 
444
870
  **Step by step:**
445
871
 
@@ -460,6 +886,19 @@ if (result?.type === 'recovery') {
460
886
  }
461
887
  ```
462
888
 
889
+ If you use the event-based pattern instead of checking `result.type`, listen for the `'recovery'` event:
890
+
891
+ ```ts
892
+ import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
893
+
894
+ onAuthChange((event, user) => {
895
+ if (event === AUTH_EVENTS.RECOVERY) {
896
+ // Redirect to password reset form.
897
+ // The user is authenticated, so call updateUser({ password }) to set the new password.
898
+ }
899
+ })
900
+ ```
901
+
463
902
  ### Invite acceptance
464
903
 
465
904
  When an admin invites a user, they receive an email with an invite link. Clicking it redirects to your site with an `invite_token` in the URL hash. Unlike other callback types, the user is not logged in automatically because they need to set a password first.
@@ -481,6 +920,17 @@ if (result?.type === 'invite' && result.token) {
481
920
  }
482
921
  ```
483
922
 
923
+ ### Session lifetime
924
+
925
+ Sessions are managed by Netlify Identity (GoTrue) on the server side. The library stores two cookies:
926
+
927
+ - **`nf_jwt`**: A short-lived JWT access token (default: 1 hour). Automatically refreshed by gotrue-js in the browser using the refresh token.
928
+ - **`nf_refresh`**: A long-lived refresh token used to obtain new access tokens without re-authenticating.
929
+
930
+ In the browser, gotrue-js handles token refresh automatically in the background. On the server, the access token in the `nf_jwt` cookie is validated as-is; if it has expired, `getUser()` returns `null`. The user will need to refresh the page (which triggers a browser-side token refresh) or log in again.
931
+
932
+ Session lifetime is configured in your GoTrue/Identity server settings, not in this library.
933
+
484
934
  ## License
485
935
 
486
936
  MIT