@netlify/identity 0.1.1-alpha.21 → 0.1.1-alpha.23

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
@@ -164,7 +164,7 @@ Processes the URL hash after an OAuth redirect, email confirmation, password rec
164
164
  onAuthChange(callback: AuthCallback): () => void
165
165
  ```
166
166
 
167
- 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.
167
+ 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.
168
168
 
169
169
  #### `hydrateSession`
170
170
 
@@ -323,10 +323,24 @@ interface AppMetadata {
323
323
  }
324
324
  ```
325
325
 
326
+ #### `AUTH_EVENTS`
327
+
328
+ ```ts
329
+ const AUTH_EVENTS: {
330
+ LOGIN: 'login'
331
+ LOGOUT: 'logout'
332
+ TOKEN_REFRESH: 'token_refresh'
333
+ USER_UPDATED: 'user_updated'
334
+ RECOVERY: 'recovery'
335
+ }
336
+ ```
337
+
338
+ Constants for auth event names. Use these instead of string literals for type safety and autocomplete.
339
+
326
340
  #### `AuthEvent`
327
341
 
328
342
  ```ts
329
- type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated'
343
+ type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated' | 'recovery'
330
344
  ```
331
345
 
332
346
  #### `AuthCallback`
@@ -620,32 +634,60 @@ export function load() {
620
634
 
621
635
  ### Handling OAuth callbacks in SPAs
622
636
 
623
- All SPA frameworks need a callback handler that runs on page load to process OAuth redirects, email confirmations, and password recovery tokens.
637
+ 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.
624
638
 
625
639
  ```tsx
626
640
  // React component (works with Next.js, Remix, TanStack Start)
627
- import { useEffect } from 'react'
641
+ import { useEffect, useState } from 'react'
628
642
  import { handleAuthCallback } from '@netlify/identity'
629
643
 
630
- export function CallbackHandler() {
644
+ const AUTH_HASH_PATTERN = /^#(confirmation_token|recovery_token|invite_token|email_change_token|access_token)=/
645
+
646
+ export function CallbackHandler({ children }: { children: React.ReactNode }) {
647
+ const [processing, setProcessing] = useState(
648
+ () => typeof window !== 'undefined' && AUTH_HASH_PATTERN.test(window.location.hash),
649
+ )
650
+ const [error, setError] = useState<string | null>(null)
651
+
631
652
  useEffect(() => {
632
- if (!window.location.hash) return
633
-
634
- handleAuthCallback().then((result) => {
635
- if (!result) return
636
- if (result.type === 'invite') {
637
- window.location.href = `/accept-invite?token=${result.token}`
638
- } else {
639
- window.location.href = '/dashboard'
640
- }
641
- })
653
+ if (!window.location.hash || !AUTH_HASH_PATTERN.test(window.location.hash)) return
654
+
655
+ handleAuthCallback()
656
+ .then((result) => {
657
+ if (!result) {
658
+ setProcessing(false)
659
+ return
660
+ }
661
+ if (result.type === 'invite') {
662
+ window.location.href = `/accept-invite?token=${result.token}`
663
+ } else if (result.type === 'recovery') {
664
+ window.location.href = '/reset-password'
665
+ } else {
666
+ window.location.href = '/dashboard'
667
+ }
668
+ })
669
+ .catch((err) => {
670
+ setError(err instanceof Error ? err.message : 'Callback failed')
671
+ setProcessing(false)
672
+ })
642
673
  }, [])
643
674
 
644
- return null
675
+ if (error) return <div>Auth error: {error}</div>
676
+ if (processing) return <div>Confirming your account...</div>
677
+ return <>{children}</>
645
678
  }
646
679
  ```
647
680
 
648
- Mount this component in your **root layout** so it runs on every page. If you only mount it on a `/callback` route, OAuth redirects and email confirmation links that land on other pages will not be processed.
681
+ Wrap your page content with this component in your **root layout** so it runs on every page:
682
+
683
+ ```tsx
684
+ // Root layout
685
+ <CallbackHandler>
686
+ <Outlet /> {/* or {children} in Next.js */}
687
+ </CallbackHandler>
688
+ ```
689
+
690
+ If you only mount it on a `/callback` route, OAuth redirects and email confirmation links that land on other pages will not be processed.
649
691
 
650
692
  ## Guides
651
693
 
@@ -678,25 +720,29 @@ function NavBar() {
678
720
 
679
721
  ### Listening for auth changes
680
722
 
681
- 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`).
723
+ 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`).
682
724
 
683
725
  ```ts
684
- import { onAuthChange } from '@netlify/identity'
726
+ import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
685
727
 
686
728
  const unsubscribe = onAuthChange((event, user) => {
687
729
  switch (event) {
688
- case 'login':
730
+ case AUTH_EVENTS.LOGIN:
689
731
  console.log('Logged in:', user?.email)
690
732
  break
691
- case 'logout':
733
+ case AUTH_EVENTS.LOGOUT:
692
734
  console.log('Logged out')
693
735
  break
694
- case 'token_refresh':
736
+ case AUTH_EVENTS.TOKEN_REFRESH:
695
737
  console.log('Token refreshed for:', user?.email)
696
738
  break
697
- case 'user_updated':
739
+ case AUTH_EVENTS.USER_UPDATED:
698
740
  console.log('User updated:', user?.email)
699
741
  break
742
+ case AUTH_EVENTS.RECOVERY:
743
+ console.log('Recovery login:', user?.email)
744
+ // Redirect to password reset form, then call updateUser({ password })
745
+ break
700
746
  }
701
747
  })
702
748
 
@@ -729,11 +775,11 @@ if (result?.type === 'oauth') {
729
775
  }
730
776
  ```
731
777
 
732
- `handleAuthCallback()` exchanges the token in the URL hash, logs the user in, clears the hash, and emits a `'login'` event via `onAuthChange`.
778
+ `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).
733
779
 
734
780
  ### Password recovery
735
781
 
736
- 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.
782
+ 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.
737
783
 
738
784
  **Step by step:**
739
785
 
@@ -754,6 +800,19 @@ if (result?.type === 'recovery') {
754
800
  }
755
801
  ```
756
802
 
803
+ If you use the event-based pattern instead of checking `result.type`, listen for the `'recovery'` event:
804
+
805
+ ```ts
806
+ import { onAuthChange, AUTH_EVENTS } from '@netlify/identity'
807
+
808
+ onAuthChange((event, user) => {
809
+ if (event === AUTH_EVENTS.RECOVERY) {
810
+ // Redirect to password reset form.
811
+ // The user is authenticated, so call updateUser({ password }) to set the new password.
812
+ }
813
+ })
814
+ ```
815
+
757
816
  ### Invite acceptance
758
817
 
759
818
  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.
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AUTH_EVENTS: () => AUTH_EVENTS,
33
34
  AuthError: () => AuthError,
34
35
  MissingIdentityError: () => MissingIdentityError,
35
36
  acceptInvite: () => acceptInvite,
@@ -348,22 +349,15 @@ var getSettings = async () => {
348
349
  }
349
350
  };
350
351
 
351
- // src/auth.ts
352
- var getCookies = () => {
353
- const cookies = globalThis.Netlify?.context?.cookies;
354
- if (!cookies) {
355
- throw new AuthError("Server-side auth requires Netlify Functions runtime");
356
- }
357
- return cookies;
352
+ // src/events.ts
353
+ var AUTH_EVENTS = {
354
+ LOGIN: "login",
355
+ LOGOUT: "logout",
356
+ TOKEN_REFRESH: "token_refresh",
357
+ USER_UPDATED: "user_updated",
358
+ RECOVERY: "recovery"
358
359
  };
359
- var getServerIdentityUrl = () => {
360
- const ctx = getIdentityContext();
361
- if (!ctx?.url) {
362
- throw new AuthError("Could not determine the Identity endpoint URL on the server");
363
- }
364
- return ctx.url;
365
- };
366
- var persistSession = true;
360
+ var GOTRUE_STORAGE_KEY = "gotrue.user";
367
361
  var listeners = /* @__PURE__ */ new Set();
368
362
  var emitAuthEvent = (event, user) => {
369
363
  for (const listener of listeners) {
@@ -373,19 +367,18 @@ var emitAuthEvent = (event, user) => {
373
367
  }
374
368
  }
375
369
  };
376
- var GOTRUE_STORAGE_KEY = "gotrue.user";
377
370
  var storageListenerAttached = false;
378
371
  var attachStorageListener = () => {
379
- if (storageListenerAttached) return;
372
+ if (storageListenerAttached || !isBrowser()) return;
380
373
  storageListenerAttached = true;
381
374
  window.addEventListener("storage", (event) => {
382
375
  if (event.key !== GOTRUE_STORAGE_KEY) return;
383
376
  if (event.newValue) {
384
377
  const client = getGoTrueClient();
385
378
  const currentUser = client?.currentUser();
386
- emitAuthEvent("login", currentUser ? toUser(currentUser) : null);
379
+ emitAuthEvent(AUTH_EVENTS.LOGIN, currentUser ? toUser(currentUser) : null);
387
380
  } else {
388
- emitAuthEvent("logout", null);
381
+ emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
389
382
  }
390
383
  });
391
384
  };
@@ -400,6 +393,23 @@ var onAuthChange = (callback) => {
400
393
  listeners.delete(callback);
401
394
  };
402
395
  };
396
+
397
+ // src/auth.ts
398
+ var getCookies = () => {
399
+ const cookies = globalThis.Netlify?.context?.cookies;
400
+ if (!cookies) {
401
+ throw new AuthError("Server-side auth requires Netlify Functions runtime");
402
+ }
403
+ return cookies;
404
+ };
405
+ var getServerIdentityUrl = () => {
406
+ const ctx = getIdentityContext();
407
+ if (!ctx?.url) {
408
+ throw new AuthError("Could not determine the Identity endpoint URL on the server");
409
+ }
410
+ return ctx.url;
411
+ };
412
+ var persistSession = true;
403
413
  var login = async (email, password) => {
404
414
  if (!isBrowser()) {
405
415
  const identityUrl = getServerIdentityUrl();
@@ -421,10 +431,7 @@ var login = async (email, password) => {
421
431
  }
422
432
  if (!res.ok) {
423
433
  const errorBody = await res.json().catch(() => ({}));
424
- throw new AuthError(
425
- errorBody.msg || errorBody.error_description || `Login failed (${res.status})`,
426
- res.status
427
- );
434
+ throw new AuthError(errorBody.msg || errorBody.error_description || `Login failed (${res.status})`, res.status);
428
435
  }
429
436
  const data = await res.json();
430
437
  const accessToken = data.access_token;
@@ -438,10 +445,7 @@ var login = async (email, password) => {
438
445
  }
439
446
  if (!userRes.ok) {
440
447
  const errorBody = await userRes.json().catch(() => ({}));
441
- throw new AuthError(
442
- errorBody.msg || `Failed to fetch user data (${userRes.status})`,
443
- userRes.status
444
- );
448
+ throw new AuthError(errorBody.msg || `Failed to fetch user data (${userRes.status})`, userRes.status);
445
449
  }
446
450
  const userData = await userRes.json();
447
451
  const user = toUser(userData);
@@ -454,7 +458,7 @@ var login = async (email, password) => {
454
458
  const jwt = await gotrueUser.jwt();
455
459
  setBrowserAuthCookies(jwt);
456
460
  const user = toUser(gotrueUser);
457
- emitAuthEvent("login", user);
461
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
458
462
  return user;
459
463
  } catch (error) {
460
464
  throw new AuthError(error.message, void 0, { cause: error });
@@ -481,10 +485,9 @@ var signup = async (email, password, data) => {
481
485
  const responseData = await res.json();
482
486
  const user = toUser(responseData);
483
487
  if (responseData.confirmed_at) {
484
- const responseRecord = responseData;
485
- const accessToken = responseRecord.access_token;
488
+ const accessToken = responseData.access_token;
486
489
  if (accessToken) {
487
- setAuthCookies(cookies, accessToken, responseRecord.refresh_token);
490
+ setAuthCookies(cookies, accessToken, responseData.refresh_token);
488
491
  }
489
492
  }
490
493
  return user;
@@ -498,7 +501,7 @@ var signup = async (email, password, data) => {
498
501
  if (jwt) {
499
502
  setBrowserAuthCookies(jwt);
500
503
  }
501
- emitAuthEvent("login", user);
504
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
502
505
  }
503
506
  return user;
504
507
  } catch (error) {
@@ -529,7 +532,7 @@ var logout = async () => {
529
532
  await currentUser.logout();
530
533
  }
531
534
  deleteBrowserAuthCookies();
532
- emitAuthEvent("logout", null);
535
+ emitAuthEvent(AUTH_EVENTS.LOGOUT, null);
533
536
  } catch (error) {
534
537
  throw new AuthError(error.message, void 0, { cause: error });
535
538
  }
@@ -565,7 +568,7 @@ var handleAuthCallback = async () => {
565
568
  setBrowserAuthCookies(accessToken, refreshToken || void 0);
566
569
  const user = toUser(gotrueUser);
567
570
  clearHash();
568
- emitAuthEvent("login", user);
571
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
569
572
  return { type: "oauth", user };
570
573
  }
571
574
  const confirmationToken = params.get("confirmation_token");
@@ -575,7 +578,7 @@ var handleAuthCallback = async () => {
575
578
  setBrowserAuthCookies(jwt);
576
579
  const user = toUser(gotrueUser);
577
580
  clearHash();
578
- emitAuthEvent("login", user);
581
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
579
582
  return { type: "confirmation", user };
580
583
  }
581
584
  const recoveryToken = params.get("recovery_token");
@@ -585,7 +588,7 @@ var handleAuthCallback = async () => {
585
588
  setBrowserAuthCookies(jwt);
586
589
  const user = toUser(gotrueUser);
587
590
  clearHash();
588
- emitAuthEvent("login", user);
591
+ emitAuthEvent(AUTH_EVENTS.RECOVERY, user);
589
592
  return { type: "recovery", user };
590
593
  }
591
594
  const inviteToken = params.get("invite_token");
@@ -619,7 +622,7 @@ var handleAuthCallback = async () => {
619
622
  const emailChangeData = await emailChangeRes.json();
620
623
  const user = toUser(emailChangeData);
621
624
  clearHash();
622
- emitAuthEvent("user_updated", user);
625
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
623
626
  return { type: "email_change", user };
624
627
  }
625
628
  return null;
@@ -653,12 +656,12 @@ var hydrateSession = async () => {
653
656
  persistSession
654
657
  );
655
658
  const user = toUser(gotrueUser);
656
- emitAuthEvent("login", user);
659
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
657
660
  return user;
658
661
  };
659
662
 
660
663
  // src/account.ts
661
- var ensureCurrentUser = async () => {
664
+ var resolveCurrentUser = async () => {
662
665
  const client = getClient();
663
666
  let currentUser = client.currentUser();
664
667
  if (!currentUser && isBrowser()) {
@@ -685,7 +688,7 @@ var recoverPassword = async (token, newPassword) => {
685
688
  const gotrueUser = await client.recover(token, persistSession);
686
689
  const updatedUser = await gotrueUser.update({ password: newPassword });
687
690
  const user = toUser(updatedUser);
688
- emitAuthEvent("login", user);
691
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
689
692
  return user;
690
693
  } catch (error) {
691
694
  throw new AuthError(error.message, void 0, { cause: error });
@@ -696,7 +699,7 @@ var confirmEmail = async (token) => {
696
699
  try {
697
700
  const gotrueUser = await client.confirm(token, persistSession);
698
701
  const user = toUser(gotrueUser);
699
- emitAuthEvent("login", user);
702
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
700
703
  return user;
701
704
  } catch (error) {
702
705
  throw new AuthError(error.message, void 0, { cause: error });
@@ -707,7 +710,7 @@ var acceptInvite = async (token, password) => {
707
710
  try {
708
711
  const gotrueUser = await client.acceptInvite(token, password, persistSession);
709
712
  const user = toUser(gotrueUser);
710
- emitAuthEvent("login", user);
713
+ emitAuthEvent(AUTH_EVENTS.LOGIN, user);
711
714
  return user;
712
715
  } catch (error) {
713
716
  throw new AuthError(error.message, void 0, { cause: error });
@@ -715,7 +718,7 @@ var acceptInvite = async (token, password) => {
715
718
  };
716
719
  var verifyEmailChange = async (token) => {
717
720
  if (!isBrowser()) throw new AuthError("verifyEmailChange() is only available in the browser");
718
- const currentUser = await ensureCurrentUser();
721
+ const currentUser = await resolveCurrentUser();
719
722
  const jwt = await currentUser.jwt();
720
723
  const identityUrl = `${window.location.origin}${IDENTITY_PATH}`;
721
724
  try {
@@ -729,14 +732,11 @@ var verifyEmailChange = async (token) => {
729
732
  });
730
733
  if (!res.ok) {
731
734
  const errorBody = await res.json().catch(() => ({}));
732
- throw new AuthError(
733
- errorBody.msg || `Email change verification failed (${res.status})`,
734
- res.status
735
- );
735
+ throw new AuthError(errorBody.msg || `Email change verification failed (${res.status})`, res.status);
736
736
  }
737
737
  const userData = await res.json();
738
738
  const user = toUser(userData);
739
- emitAuthEvent("user_updated", user);
739
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
740
740
  return user;
741
741
  } catch (error) {
742
742
  if (error instanceof AuthError) throw error;
@@ -744,11 +744,11 @@ var verifyEmailChange = async (token) => {
744
744
  }
745
745
  };
746
746
  var updateUser = async (updates) => {
747
- const currentUser = await ensureCurrentUser();
747
+ const currentUser = await resolveCurrentUser();
748
748
  try {
749
749
  const updatedUser = await currentUser.update(updates);
750
750
  const user = toUser(updatedUser);
751
- emitAuthEvent("user_updated", user);
751
+ emitAuthEvent(AUTH_EVENTS.USER_UPDATED, user);
752
752
  return user;
753
753
  } catch (error) {
754
754
  throw new AuthError(error.message, void 0, { cause: error });
@@ -756,6 +756,7 @@ var updateUser = async (updates) => {
756
756
  };
757
757
  // Annotate the CommonJS export names for ESM import in node:
758
758
  0 && (module.exports = {
759
+ AUTH_EVENTS,
759
760
  AuthError,
760
761
  MissingIdentityError,
761
762
  acceptInvite,