@netlify/identity 0.1.1-alpha.9 → 0.2.0
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 +486 -29
- package/dist/index.cjs +268 -165
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +141 -23
- package/dist/index.d.ts +141 -23
- package/dist/index.js +273 -165
- package/dist/index.js.map +1 -1
- package/package.json +10 -2
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
|
-
###
|
|
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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
|
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?:
|
|
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
|
-
|
|
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:**
|
|
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. `
|
|
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:
|
|
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
|
|
|
@@ -264,6 +317,27 @@ interface IdentityConfig {
|
|
|
264
317
|
type AuthProvider = 'google' | 'github' | 'gitlab' | 'bitbucket' | 'facebook' | 'saml' | 'email'
|
|
265
318
|
```
|
|
266
319
|
|
|
320
|
+
#### `UserUpdates`
|
|
321
|
+
|
|
322
|
+
```ts
|
|
323
|
+
interface UserUpdates {
|
|
324
|
+
email?: string
|
|
325
|
+
password?: string
|
|
326
|
+
data?: Record<string, unknown>
|
|
327
|
+
[key: string]: unknown
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Fields accepted by `updateUser()`. All fields are optional.
|
|
332
|
+
|
|
333
|
+
#### `SignupData`
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
type SignupData = Record<string, unknown>
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
User metadata passed as the third argument to `signup()`. Stored in the user's `user_metadata` field.
|
|
340
|
+
|
|
267
341
|
#### `AppMetadata`
|
|
268
342
|
|
|
269
343
|
```ts
|
|
@@ -274,10 +348,32 @@ interface AppMetadata {
|
|
|
274
348
|
}
|
|
275
349
|
```
|
|
276
350
|
|
|
351
|
+
#### `AUTH_EVENTS`
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
const AUTH_EVENTS: {
|
|
355
|
+
LOGIN: 'login'
|
|
356
|
+
LOGOUT: 'logout'
|
|
357
|
+
TOKEN_REFRESH: 'token_refresh'
|
|
358
|
+
USER_UPDATED: 'user_updated'
|
|
359
|
+
RECOVERY: 'recovery'
|
|
360
|
+
}
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
Constants for auth event names. Use these instead of string literals for type safety and autocomplete.
|
|
364
|
+
|
|
365
|
+
| Event | When it fires |
|
|
366
|
+
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
367
|
+
| `LOGIN` | `login()`, `signup()` (with autoconfirm), `recoverPassword()`, `handleAuthCallback()` (OAuth/confirmation), `hydrateSession()` |
|
|
368
|
+
| `LOGOUT` | `logout()` |
|
|
369
|
+
| `TOKEN_REFRESH` | gotrue-js refreshes an expiring access token in the background |
|
|
370
|
+
| `USER_UPDATED` | `updateUser()`, `verifyEmailChange()`, `handleAuthCallback()` (email change) |
|
|
371
|
+
| `RECOVERY` | `handleAuthCallback()` (recovery token only). The user is authenticated but has **not** set a new password yet. Listen for this to redirect to a password reset form. `recoverPassword()` emits `LOGIN` instead because it completes both steps (token redemption + password change). |
|
|
372
|
+
|
|
277
373
|
#### `AuthEvent`
|
|
278
374
|
|
|
279
375
|
```ts
|
|
280
|
-
type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated'
|
|
376
|
+
type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated' | 'recovery'
|
|
281
377
|
```
|
|
282
378
|
|
|
283
379
|
#### `AuthCallback`
|
|
@@ -300,7 +396,6 @@ The `token` field is only present for `invite` callbacks, where the user hasn't
|
|
|
300
396
|
|
|
301
397
|
For all other types (`oauth`, `confirmation`, `recovery`, `email_change`), the user is logged in directly and `token` is not set.
|
|
302
398
|
|
|
303
|
-
|
|
304
399
|
### Errors
|
|
305
400
|
|
|
306
401
|
#### `AuthError`
|
|
@@ -320,29 +415,367 @@ class MissingIdentityError extends Error {}
|
|
|
320
415
|
|
|
321
416
|
Thrown when Identity is not configured in the current environment.
|
|
322
417
|
|
|
418
|
+
## Framework integration
|
|
419
|
+
|
|
420
|
+
### Recommended pattern for SSR frameworks
|
|
421
|
+
|
|
422
|
+
For SSR frameworks (Next.js, Remix, Astro, TanStack Start), the recommended pattern is:
|
|
423
|
+
|
|
424
|
+
- **Browser-side** for auth mutations: `login()`, `signup()`, `logout()`, `oauthLogin()`
|
|
425
|
+
- **Server-side** for reading auth state: `getUser()`, `getSettings()`, `getIdentityConfig()`
|
|
426
|
+
|
|
427
|
+
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.
|
|
428
|
+
|
|
429
|
+
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.
|
|
430
|
+
|
|
431
|
+
### Next.js (App Router)
|
|
432
|
+
|
|
433
|
+
**Server Actions return results; the client handles navigation:**
|
|
434
|
+
|
|
435
|
+
```tsx
|
|
436
|
+
// app/actions.ts
|
|
437
|
+
'use server'
|
|
438
|
+
import { login, logout } from '@netlify/identity'
|
|
439
|
+
|
|
440
|
+
export async function loginAction(formData: FormData) {
|
|
441
|
+
const email = formData.get('email') as string
|
|
442
|
+
const password = formData.get('password') as string
|
|
443
|
+
await login(email, password)
|
|
444
|
+
return { success: true }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export async function logoutAction() {
|
|
448
|
+
await logout()
|
|
449
|
+
return { success: true }
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
```tsx
|
|
454
|
+
// app/login/page.tsx
|
|
455
|
+
'use client'
|
|
456
|
+
import { loginAction } from '../actions'
|
|
457
|
+
|
|
458
|
+
export default function LoginPage() {
|
|
459
|
+
async function handleSubmit(formData: FormData) {
|
|
460
|
+
const result = await loginAction(formData)
|
|
461
|
+
if (result.success) {
|
|
462
|
+
window.location.href = '/dashboard' // full page load
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return <form action={handleSubmit}>...</form>
|
|
467
|
+
}
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
```tsx
|
|
471
|
+
// app/dashboard/page.tsx
|
|
472
|
+
import { getUser } from '@netlify/identity'
|
|
473
|
+
import { redirect } from 'next/navigation'
|
|
474
|
+
|
|
475
|
+
export default function Dashboard() {
|
|
476
|
+
const user = getUser()
|
|
477
|
+
if (!user) redirect('/login')
|
|
478
|
+
|
|
479
|
+
return <h1>Hello, {user.email}</h1>
|
|
480
|
+
}
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
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).
|
|
484
|
+
|
|
485
|
+
### Remix
|
|
486
|
+
|
|
487
|
+
**Login with Action (server-side pattern):**
|
|
488
|
+
|
|
489
|
+
```tsx
|
|
490
|
+
// app/routes/login.tsx
|
|
491
|
+
import { login } from '@netlify/identity'
|
|
492
|
+
import { redirect, json } from '@remix-run/node'
|
|
493
|
+
import type { ActionFunctionArgs } from '@remix-run/node'
|
|
494
|
+
|
|
495
|
+
export async function action({ request }: ActionFunctionArgs) {
|
|
496
|
+
const formData = await request.formData()
|
|
497
|
+
const email = formData.get('email') as string
|
|
498
|
+
const password = formData.get('password') as string
|
|
499
|
+
|
|
500
|
+
try {
|
|
501
|
+
await login(email, password)
|
|
502
|
+
return redirect('/dashboard')
|
|
503
|
+
} catch (error) {
|
|
504
|
+
return json({ error: (error as Error).message }, { status: 400 })
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
```tsx
|
|
510
|
+
// app/routes/dashboard.tsx
|
|
511
|
+
import { getUser } from '@netlify/identity'
|
|
512
|
+
import { redirect } from '@remix-run/node'
|
|
513
|
+
|
|
514
|
+
export async function loader() {
|
|
515
|
+
const user = getUser()
|
|
516
|
+
if (!user) return redirect('/login')
|
|
517
|
+
return { user }
|
|
518
|
+
}
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
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.
|
|
522
|
+
|
|
523
|
+
### TanStack Start
|
|
524
|
+
|
|
525
|
+
**Login from the browser (recommended):**
|
|
526
|
+
|
|
527
|
+
```tsx
|
|
528
|
+
// app/server/auth.ts - server functions for reads only
|
|
529
|
+
import { createServerFn } from '@tanstack/react-start'
|
|
530
|
+
import { getUser } from '@netlify/identity'
|
|
531
|
+
|
|
532
|
+
export const getServerUser = createServerFn({ method: 'GET' }).handler(async () => {
|
|
533
|
+
const user = getUser()
|
|
534
|
+
return user ?? null
|
|
535
|
+
})
|
|
536
|
+
```
|
|
537
|
+
|
|
538
|
+
```tsx
|
|
539
|
+
// app/routes/login.tsx - browser-side auth for mutations
|
|
540
|
+
import { login, signup, onAuthChange } from '@netlify/identity'
|
|
541
|
+
import { getServerUser } from '~/server/auth'
|
|
542
|
+
|
|
543
|
+
export const Route = createFileRoute('/login')({
|
|
544
|
+
beforeLoad: async () => {
|
|
545
|
+
const user = await getServerUser()
|
|
546
|
+
if (user) throw redirect({ to: '/dashboard' })
|
|
547
|
+
},
|
|
548
|
+
component: Login,
|
|
549
|
+
})
|
|
550
|
+
|
|
551
|
+
function Login() {
|
|
552
|
+
const handleLogin = async (email: string, password: string) => {
|
|
553
|
+
await login(email, password) // browser-side: sets cookie + localStorage
|
|
554
|
+
window.location.href = '/dashboard'
|
|
555
|
+
}
|
|
556
|
+
// ...
|
|
557
|
+
}
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
```tsx
|
|
561
|
+
// app/routes/dashboard.tsx
|
|
562
|
+
import { logout } from '@netlify/identity'
|
|
563
|
+
import { getServerUser } from '~/server/auth'
|
|
564
|
+
|
|
565
|
+
export const Route = createFileRoute('/dashboard')({
|
|
566
|
+
beforeLoad: async () => {
|
|
567
|
+
const user = await getServerUser()
|
|
568
|
+
if (!user) throw redirect({ to: '/login' })
|
|
569
|
+
},
|
|
570
|
+
loader: async () => {
|
|
571
|
+
const user = await getServerUser()
|
|
572
|
+
return { user: user! }
|
|
573
|
+
},
|
|
574
|
+
component: Dashboard,
|
|
575
|
+
})
|
|
576
|
+
|
|
577
|
+
function Dashboard() {
|
|
578
|
+
const { user } = Route.useLoaderData()
|
|
579
|
+
|
|
580
|
+
const handleLogout = async () => {
|
|
581
|
+
await logout() // browser-side: clears cookie + localStorage
|
|
582
|
+
window.location.href = '/'
|
|
583
|
+
}
|
|
584
|
+
// ...
|
|
585
|
+
}
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
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.
|
|
589
|
+
|
|
590
|
+
### Astro (SSR)
|
|
591
|
+
|
|
592
|
+
**Login via API endpoint (server-side pattern):**
|
|
593
|
+
|
|
594
|
+
```ts
|
|
595
|
+
// src/pages/api/login.ts
|
|
596
|
+
import type { APIRoute } from 'astro'
|
|
597
|
+
import { login } from '@netlify/identity'
|
|
598
|
+
|
|
599
|
+
export const POST: APIRoute = async ({ request }) => {
|
|
600
|
+
const { email, password } = await request.json()
|
|
601
|
+
|
|
602
|
+
try {
|
|
603
|
+
await login(email, password)
|
|
604
|
+
return new Response(null, {
|
|
605
|
+
status: 302,
|
|
606
|
+
headers: { Location: '/dashboard' },
|
|
607
|
+
})
|
|
608
|
+
} catch (error) {
|
|
609
|
+
return Response.json({ error: (error as Error).message }, { status: 400 })
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
```astro
|
|
615
|
+
---
|
|
616
|
+
// src/pages/dashboard.astro
|
|
617
|
+
import { getUser } from '@netlify/identity'
|
|
618
|
+
|
|
619
|
+
const user = getUser()
|
|
620
|
+
if (!user) return Astro.redirect('/login')
|
|
621
|
+
---
|
|
622
|
+
<h1>Hello, {user.email}</h1>
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
### SvelteKit
|
|
626
|
+
|
|
627
|
+
**Login from the browser (recommended):**
|
|
628
|
+
|
|
629
|
+
```svelte
|
|
630
|
+
<!-- src/routes/login/+page.svelte -->
|
|
631
|
+
<script lang="ts">
|
|
632
|
+
import { login } from '@netlify/identity'
|
|
633
|
+
|
|
634
|
+
let email = ''
|
|
635
|
+
let password = ''
|
|
636
|
+
let error = ''
|
|
637
|
+
|
|
638
|
+
async function handleLogin() {
|
|
639
|
+
try {
|
|
640
|
+
await login(email, password)
|
|
641
|
+
window.location.href = '/dashboard'
|
|
642
|
+
} catch (e) {
|
|
643
|
+
error = (e as Error).message
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
</script>
|
|
647
|
+
|
|
648
|
+
<form on:submit|preventDefault={handleLogin}>
|
|
649
|
+
<input bind:value={email} type="email" />
|
|
650
|
+
<input bind:value={password} type="password" />
|
|
651
|
+
<button type="submit">Log in</button>
|
|
652
|
+
{#if error}<p>{error}</p>{/if}
|
|
653
|
+
</form>
|
|
654
|
+
```
|
|
655
|
+
|
|
656
|
+
```ts
|
|
657
|
+
// src/routes/dashboard/+page.server.ts
|
|
658
|
+
import { getUser } from '@netlify/identity'
|
|
659
|
+
import { redirect } from '@sveltejs/kit'
|
|
660
|
+
|
|
661
|
+
export function load() {
|
|
662
|
+
const user = getUser()
|
|
663
|
+
if (!user) redirect(302, '/login')
|
|
664
|
+
return { user }
|
|
665
|
+
}
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
### Handling OAuth callbacks in SPAs
|
|
669
|
+
|
|
670
|
+
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.
|
|
671
|
+
|
|
672
|
+
```tsx
|
|
673
|
+
// React component (works with Next.js, Remix, TanStack Start)
|
|
674
|
+
import { useEffect, useState } from 'react'
|
|
675
|
+
import { handleAuthCallback } from '@netlify/identity'
|
|
676
|
+
|
|
677
|
+
const AUTH_HASH_PATTERN = /^#(confirmation_token|recovery_token|invite_token|email_change_token|access_token)=/
|
|
678
|
+
|
|
679
|
+
export function CallbackHandler({ children }: { children: React.ReactNode }) {
|
|
680
|
+
const [processing, setProcessing] = useState(
|
|
681
|
+
() => typeof window !== 'undefined' && AUTH_HASH_PATTERN.test(window.location.hash),
|
|
682
|
+
)
|
|
683
|
+
const [error, setError] = useState<string | null>(null)
|
|
684
|
+
|
|
685
|
+
useEffect(() => {
|
|
686
|
+
if (!window.location.hash || !AUTH_HASH_PATTERN.test(window.location.hash)) return
|
|
687
|
+
|
|
688
|
+
handleAuthCallback()
|
|
689
|
+
.then((result) => {
|
|
690
|
+
if (!result) {
|
|
691
|
+
setProcessing(false)
|
|
692
|
+
return
|
|
693
|
+
}
|
|
694
|
+
if (result.type === 'invite') {
|
|
695
|
+
window.location.href = `/accept-invite?token=${result.token}`
|
|
696
|
+
} else if (result.type === 'recovery') {
|
|
697
|
+
window.location.href = '/reset-password'
|
|
698
|
+
} else {
|
|
699
|
+
window.location.href = '/dashboard'
|
|
700
|
+
}
|
|
701
|
+
})
|
|
702
|
+
.catch((err) => {
|
|
703
|
+
setError(err instanceof Error ? err.message : 'Callback failed')
|
|
704
|
+
setProcessing(false)
|
|
705
|
+
})
|
|
706
|
+
}, [])
|
|
707
|
+
|
|
708
|
+
if (error) return <div>Auth error: {error}</div>
|
|
709
|
+
if (processing) return <div>Confirming your account...</div>
|
|
710
|
+
return <>{children}</>
|
|
711
|
+
}
|
|
712
|
+
```
|
|
713
|
+
|
|
714
|
+
Wrap your page content with this component in your **root layout** so it runs on every page:
|
|
715
|
+
|
|
716
|
+
```tsx
|
|
717
|
+
// Root layout
|
|
718
|
+
<CallbackHandler>
|
|
719
|
+
<Outlet /> {/* or {children} in Next.js */}
|
|
720
|
+
</CallbackHandler>
|
|
721
|
+
```
|
|
722
|
+
|
|
723
|
+
If you only mount it on a `/callback` route, OAuth redirects and email confirmation links that land on other pages will not be processed.
|
|
724
|
+
|
|
323
725
|
## Guides
|
|
324
726
|
|
|
727
|
+
### React `useAuth` hook
|
|
728
|
+
|
|
729
|
+
The library is framework-agnostic, but here's a simple React hook for keeping components in sync with auth state:
|
|
730
|
+
|
|
731
|
+
```tsx
|
|
732
|
+
import { useState, useEffect } from 'react'
|
|
733
|
+
import { getUser, onAuthChange } from '@netlify/identity'
|
|
734
|
+
import type { User } from '@netlify/identity'
|
|
735
|
+
|
|
736
|
+
export function useAuth() {
|
|
737
|
+
const [user, setUser] = useState<User | null>(getUser())
|
|
738
|
+
|
|
739
|
+
useEffect(() => {
|
|
740
|
+
return onAuthChange((_event, user) => setUser(user))
|
|
741
|
+
}, [])
|
|
742
|
+
|
|
743
|
+
return user
|
|
744
|
+
}
|
|
745
|
+
```
|
|
746
|
+
|
|
747
|
+
```tsx
|
|
748
|
+
function NavBar() {
|
|
749
|
+
const user = useAuth()
|
|
750
|
+
return user ? <p>Hello, {user.name}</p> : <a href="/login">Log in</a>
|
|
751
|
+
}
|
|
752
|
+
```
|
|
753
|
+
|
|
325
754
|
### Listening for auth changes
|
|
326
755
|
|
|
327
|
-
Use `onAuthChange` to keep your UI in sync with auth state. It fires on login, logout, token refresh,
|
|
756
|
+
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`).
|
|
328
757
|
|
|
329
758
|
```ts
|
|
330
|
-
import { onAuthChange } from '@netlify/identity'
|
|
759
|
+
import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
|
|
331
760
|
|
|
332
761
|
const unsubscribe = onAuthChange((event, user) => {
|
|
333
762
|
switch (event) {
|
|
334
|
-
case
|
|
763
|
+
case AUTH_EVENTS.LOGIN:
|
|
335
764
|
console.log('Logged in:', user?.email)
|
|
336
765
|
break
|
|
337
|
-
case
|
|
766
|
+
case AUTH_EVENTS.LOGOUT:
|
|
338
767
|
console.log('Logged out')
|
|
339
768
|
break
|
|
340
|
-
case
|
|
769
|
+
case AUTH_EVENTS.TOKEN_REFRESH:
|
|
341
770
|
console.log('Token refreshed for:', user?.email)
|
|
342
771
|
break
|
|
343
|
-
case
|
|
772
|
+
case AUTH_EVENTS.USER_UPDATED:
|
|
344
773
|
console.log('User updated:', user?.email)
|
|
345
774
|
break
|
|
775
|
+
case AUTH_EVENTS.RECOVERY:
|
|
776
|
+
console.log('Recovery login:', user?.email)
|
|
777
|
+
// Redirect to password reset form, then call updateUser({ password })
|
|
778
|
+
break
|
|
346
779
|
}
|
|
347
780
|
})
|
|
348
781
|
|
|
@@ -375,11 +808,11 @@ if (result?.type === 'oauth') {
|
|
|
375
808
|
}
|
|
376
809
|
```
|
|
377
810
|
|
|
378
|
-
`handleAuthCallback()` exchanges the token in the URL hash, logs the user in, clears the hash, and emits
|
|
811
|
+
`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).
|
|
379
812
|
|
|
380
813
|
### Password recovery
|
|
381
814
|
|
|
382
|
-
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.
|
|
815
|
+
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.
|
|
383
816
|
|
|
384
817
|
**Step by step:**
|
|
385
818
|
|
|
@@ -400,6 +833,19 @@ if (result?.type === 'recovery') {
|
|
|
400
833
|
}
|
|
401
834
|
```
|
|
402
835
|
|
|
836
|
+
If you use the event-based pattern instead of checking `result.type`, listen for the `'recovery'` event:
|
|
837
|
+
|
|
838
|
+
```ts
|
|
839
|
+
import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
|
|
840
|
+
|
|
841
|
+
onAuthChange((event, user) => {
|
|
842
|
+
if (event === AUTH_EVENTS.RECOVERY) {
|
|
843
|
+
// Redirect to password reset form.
|
|
844
|
+
// The user is authenticated, so call updateUser({ password }) to set the new password.
|
|
845
|
+
}
|
|
846
|
+
})
|
|
847
|
+
```
|
|
848
|
+
|
|
403
849
|
### Invite acceptance
|
|
404
850
|
|
|
405
851
|
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.
|
|
@@ -421,6 +867,17 @@ if (result?.type === 'invite' && result.token) {
|
|
|
421
867
|
}
|
|
422
868
|
```
|
|
423
869
|
|
|
870
|
+
### Session lifetime
|
|
871
|
+
|
|
872
|
+
Sessions are managed by Netlify Identity (GoTrue) on the server side. The library stores two cookies:
|
|
873
|
+
|
|
874
|
+
- **`nf_jwt`**: A short-lived JWT access token (default: 1 hour). Automatically refreshed by gotrue-js in the browser using the refresh token.
|
|
875
|
+
- **`nf_refresh`**: A long-lived refresh token used to obtain new access tokens without re-authenticating.
|
|
876
|
+
|
|
877
|
+
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.
|
|
878
|
+
|
|
879
|
+
Session lifetime is configured in your GoTrue/Identity server settings, not in this library.
|
|
880
|
+
|
|
424
881
|
## License
|
|
425
882
|
|
|
426
883
|
MIT
|