@netlify/identity 0.1.1 → 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 +726 -13
- package/dist/index.cjs +636 -26
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +175 -5
- package/dist/index.d.ts +175 -5
- package/dist/index.js +628 -25
- 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
|
|
|
@@ -74,7 +103,7 @@ Returns the current authenticated user, or `null` if not logged in. Synchronous,
|
|
|
74
103
|
isAuthenticated(): boolean
|
|
75
104
|
```
|
|
76
105
|
|
|
77
|
-
Returns `true` if a user is currently authenticated. Equivalent to `getUser() !== null`.
|
|
106
|
+
Returns `true` if a user is currently authenticated. Equivalent to `getUser() !== null`. Never throws.
|
|
78
107
|
|
|
79
108
|
#### `getIdentityConfig`
|
|
80
109
|
|
|
@@ -90,7 +119,159 @@ Returns the Identity endpoint URL (and operator token on the server), or `null`
|
|
|
90
119
|
getSettings(): Promise<Settings>
|
|
91
120
|
```
|
|
92
121
|
|
|
93
|
-
Fetches your project's Identity settings (enabled providers, autoconfirm, signup disabled).
|
|
122
|
+
Fetches your project's Identity settings (enabled providers, autoconfirm, signup disabled).
|
|
123
|
+
|
|
124
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if the endpoint is unreachable.
|
|
125
|
+
|
|
126
|
+
#### `login`
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
login(email: string, password: string): Promise<User>
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Logs in with email and password. Works in both browser and server contexts.
|
|
133
|
+
|
|
134
|
+
In the browser, uses gotrue-js and emits a `'login'` event. On the server (Netlify Functions, Edge Functions), calls the GoTrue HTTP API directly and sets the `nf_jwt` cookie via the Netlify runtime.
|
|
135
|
+
|
|
136
|
+
**Throws:** `AuthError` on invalid credentials or network failure. In the browser, `MissingIdentityError` if Identity is not configured. On the server, `AuthError` if the Netlify Functions runtime is not available.
|
|
137
|
+
|
|
138
|
+
#### `signup`
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
signup(email: string, password: string, data?: SignupData): Promise<User>
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
Creates a new account. Works in both browser and server contexts.
|
|
145
|
+
|
|
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.
|
|
149
|
+
|
|
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.
|
|
151
|
+
|
|
152
|
+
#### `logout`
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
logout(): Promise<void>
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Logs out the current user and clears the session. Works in both browser and server contexts.
|
|
159
|
+
|
|
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.
|
|
161
|
+
|
|
162
|
+
**Throws:** In the browser, `MissingIdentityError` if Identity is not configured. On the server, `AuthError` if the Netlify Functions runtime is not available.
|
|
163
|
+
|
|
164
|
+
#### `oauthLogin`
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
oauthLogin(provider: string): never
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Redirects to an OAuth provider. The page navigates away, so this function never returns normally. Browser only.
|
|
171
|
+
|
|
172
|
+
The `provider` argument should be one of the `AuthProvider` values: `'google'`, `'github'`, `'gitlab'`, `'bitbucket'`, `'facebook'`, or `'saml'`.
|
|
173
|
+
|
|
174
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if called on the server.
|
|
175
|
+
|
|
176
|
+
#### `handleAuthCallback`
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
handleAuthCallback(): Promise<CallbackResult | null>
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Processes the URL hash after an OAuth redirect, email confirmation, password recovery, invite acceptance, or email change. Call on page load. Returns `null` if the hash contains no auth parameters. Browser only.
|
|
183
|
+
|
|
184
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if token exchange fails.
|
|
185
|
+
|
|
186
|
+
#### `onAuthChange`
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
onAuthChange(callback: AuthCallback): () => void
|
|
190
|
+
```
|
|
191
|
+
|
|
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
|
+
```
|
|
215
|
+
|
|
216
|
+
#### `requestPasswordRecovery`
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
requestPasswordRecovery(email: string): Promise<void>
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Sends a password recovery email to the given address.
|
|
223
|
+
|
|
224
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` on network failure.
|
|
225
|
+
|
|
226
|
+
#### `confirmEmail`
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
confirmEmail(token: string): Promise<User>
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Confirms an email address using the token from a confirmation email. Logs the user in on success.
|
|
233
|
+
|
|
234
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if the token is invalid or expired.
|
|
235
|
+
|
|
236
|
+
#### `acceptInvite`
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
acceptInvite(token: string, password: string): Promise<User>
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
Accepts an invite token and sets a password for the new account. Logs the user in on success.
|
|
243
|
+
|
|
244
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if the token is invalid or expired.
|
|
245
|
+
|
|
246
|
+
#### `verifyEmailChange`
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
verifyEmailChange(token: string): Promise<User>
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
Verifies an email change using the token from a verification email.
|
|
253
|
+
|
|
254
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if the token is invalid.
|
|
255
|
+
|
|
256
|
+
#### `recoverPassword`
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
recoverPassword(token: string, newPassword: string): Promise<User>
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Redeems a recovery token and sets a new password. Logs the user in on success.
|
|
263
|
+
|
|
264
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if the token is invalid or expired.
|
|
265
|
+
|
|
266
|
+
#### `updateUser`
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
updateUser(updates: UserUpdates): Promise<User>
|
|
270
|
+
```
|
|
271
|
+
|
|
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' } }`).
|
|
273
|
+
|
|
274
|
+
**Throws:** `MissingIdentityError` if Identity is not configured. `AuthError` if no user is logged in, or the update fails.
|
|
94
275
|
|
|
95
276
|
### Types
|
|
96
277
|
|
|
@@ -136,6 +317,27 @@ interface IdentityConfig {
|
|
|
136
317
|
type AuthProvider = 'google' | 'github' | 'gitlab' | 'bitbucket' | 'facebook' | 'saml' | 'email'
|
|
137
318
|
```
|
|
138
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
|
+
|
|
139
341
|
#### `AppMetadata`
|
|
140
342
|
|
|
141
343
|
```ts
|
|
@@ -146,6 +348,54 @@ interface AppMetadata {
|
|
|
146
348
|
}
|
|
147
349
|
```
|
|
148
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
|
+
|
|
373
|
+
#### `AuthEvent`
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated' | 'recovery'
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
#### `AuthCallback`
|
|
380
|
+
|
|
381
|
+
```ts
|
|
382
|
+
type AuthCallback = (event: AuthEvent, user: User | null) => void
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
#### `CallbackResult`
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
interface CallbackResult {
|
|
389
|
+
type: 'oauth' | 'confirmation' | 'recovery' | 'invite' | 'email_change'
|
|
390
|
+
user: User | null
|
|
391
|
+
token?: string
|
|
392
|
+
}
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
The `token` field is only present for `invite` callbacks, where the user hasn't set a password yet. Pass `token` to `acceptInvite(token, password)` to finish.
|
|
396
|
+
|
|
397
|
+
For all other types (`oauth`, `confirmation`, `recovery`, `email_change`), the user is logged in directly and `token` is not set.
|
|
398
|
+
|
|
149
399
|
### Errors
|
|
150
400
|
|
|
151
401
|
#### `AuthError`
|
|
@@ -165,6 +415,469 @@ class MissingIdentityError extends Error {}
|
|
|
165
415
|
|
|
166
416
|
Thrown when Identity is not configured in the current environment.
|
|
167
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
|
+
|
|
725
|
+
## Guides
|
|
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
|
+
|
|
754
|
+
### Listening for auth changes
|
|
755
|
+
|
|
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`).
|
|
757
|
+
|
|
758
|
+
```ts
|
|
759
|
+
import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
|
|
760
|
+
|
|
761
|
+
const unsubscribe = onAuthChange((event, user) => {
|
|
762
|
+
switch (event) {
|
|
763
|
+
case AUTH_EVENTS.LOGIN:
|
|
764
|
+
console.log('Logged in:', user?.email)
|
|
765
|
+
break
|
|
766
|
+
case AUTH_EVENTS.LOGOUT:
|
|
767
|
+
console.log('Logged out')
|
|
768
|
+
break
|
|
769
|
+
case AUTH_EVENTS.TOKEN_REFRESH:
|
|
770
|
+
console.log('Token refreshed for:', user?.email)
|
|
771
|
+
break
|
|
772
|
+
case AUTH_EVENTS.USER_UPDATED:
|
|
773
|
+
console.log('User updated:', user?.email)
|
|
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
|
|
779
|
+
}
|
|
780
|
+
})
|
|
781
|
+
|
|
782
|
+
// Later, to stop listening:
|
|
783
|
+
unsubscribe()
|
|
784
|
+
```
|
|
785
|
+
|
|
786
|
+
On the server, `onAuthChange` is a no-op and the returned unsubscribe function does nothing.
|
|
787
|
+
|
|
788
|
+
### OAuth login
|
|
789
|
+
|
|
790
|
+
OAuth login is a two-step flow: redirect the user to the provider, then process the callback when they return.
|
|
791
|
+
|
|
792
|
+
**Step by step:**
|
|
793
|
+
|
|
794
|
+
```ts
|
|
795
|
+
import { oauthLogin, handleAuthCallback } from '@netlify/identity'
|
|
796
|
+
|
|
797
|
+
// 1. Kick off the OAuth flow (e.g., from a "Sign in with GitHub" button).
|
|
798
|
+
// This navigates away from the page and does not return.
|
|
799
|
+
oauthLogin('github')
|
|
800
|
+
```
|
|
801
|
+
|
|
802
|
+
```ts
|
|
803
|
+
// 2. On page load, handle the redirect back from the provider.
|
|
804
|
+
const result = await handleAuthCallback()
|
|
805
|
+
|
|
806
|
+
if (result?.type === 'oauth') {
|
|
807
|
+
console.log('Logged in via OAuth:', result.user?.email)
|
|
808
|
+
}
|
|
809
|
+
```
|
|
810
|
+
|
|
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).
|
|
812
|
+
|
|
813
|
+
### Password recovery
|
|
814
|
+
|
|
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.
|
|
816
|
+
|
|
817
|
+
**Step by step:**
|
|
818
|
+
|
|
819
|
+
```ts
|
|
820
|
+
import { requestPasswordRecovery, handleAuthCallback, updateUser } from '@netlify/identity'
|
|
821
|
+
|
|
822
|
+
// 1. Send recovery email (e.g., from a "forgot password" form)
|
|
823
|
+
await requestPasswordRecovery('jane@example.com')
|
|
824
|
+
|
|
825
|
+
// 2-3. On page load, handle the callback
|
|
826
|
+
const result = await handleAuthCallback()
|
|
827
|
+
|
|
828
|
+
if (result?.type === 'recovery') {
|
|
829
|
+
// 4. User is now logged in. Show your "set new password" form.
|
|
830
|
+
// When they submit:
|
|
831
|
+
const newPassword = document.getElementById('new-password').value
|
|
832
|
+
await updateUser({ password: newPassword })
|
|
833
|
+
}
|
|
834
|
+
```
|
|
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
|
+
|
|
849
|
+
### Invite acceptance
|
|
850
|
+
|
|
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.
|
|
852
|
+
|
|
853
|
+
**Step by step:**
|
|
854
|
+
|
|
855
|
+
```ts
|
|
856
|
+
import { handleAuthCallback, acceptInvite } from '@netlify/identity'
|
|
857
|
+
|
|
858
|
+
// 1. On page load, handle the callback.
|
|
859
|
+
const result = await handleAuthCallback()
|
|
860
|
+
|
|
861
|
+
if (result?.type === 'invite' && result.token) {
|
|
862
|
+
// 2. The user is NOT logged in yet. Show a "set your password" form.
|
|
863
|
+
// When they submit:
|
|
864
|
+
const password = document.getElementById('password').value
|
|
865
|
+
const user = await acceptInvite(result.token, password)
|
|
866
|
+
console.log('Account created:', user.email)
|
|
867
|
+
}
|
|
868
|
+
```
|
|
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
|
+
|
|
168
881
|
## License
|
|
169
882
|
|
|
170
883
|
MIT
|