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

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/dist/index.d.ts CHANGED
@@ -14,6 +14,36 @@ interface Settings {
14
14
  disableSignup: boolean;
15
15
  providers: Record<AuthProvider, boolean>;
16
16
  }
17
+ /**
18
+ * Fields accepted by {@link updateUser}. All fields are optional.
19
+ * Pass `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
20
+ */
21
+ interface UserUpdates {
22
+ email?: string;
23
+ password?: string;
24
+ data?: Record<string, unknown>;
25
+ [key: string]: unknown;
26
+ }
27
+ /**
28
+ * User metadata passed during signup (e.g., `{ full_name: 'Jane Doe' }`).
29
+ * Stored in the user's `user_metadata` field.
30
+ */
31
+ type SignupData = Record<string, unknown>;
32
+ /**
33
+ * Fields accepted by {@link admin.updateUser}. All fields are optional.
34
+ *
35
+ * Unlike {@link UserUpdates} (used by the self-service `updateUser`), admin updates
36
+ * can set `role`, force-confirm a user, and write to `app_metadata`.
37
+ */
38
+ interface AdminUserUpdates {
39
+ email?: string;
40
+ password?: string;
41
+ role?: string;
42
+ confirm?: boolean;
43
+ app_metadata?: Record<string, unknown>;
44
+ user_metadata?: Record<string, unknown>;
45
+ [key: string]: unknown;
46
+ }
17
47
 
18
48
  interface User {
19
49
  id: string;
@@ -29,7 +59,16 @@ interface User {
29
59
  }
30
60
  /**
31
61
  * Returns the currently authenticated user, or `null` if not logged in.
32
- * Synchronous. Never throws.
62
+ * Synchronous.
63
+ *
64
+ * In the browser, checks gotrue-js localStorage first. If no localStorage
65
+ * session exists, falls back to decoding the `nf_jwt` cookie (set by
66
+ * server-side login) and kicks off background hydration of the gotrue-js
67
+ * session so that subsequent operations (updateUser, logout, etc.) work.
68
+ *
69
+ * On the server in a Next.js App Router context, calls `headers()` from
70
+ * `next/headers` to opt the route into dynamic rendering. Without this,
71
+ * Next.js may statically cache the page at build time.
33
72
  */
34
73
  declare const getUser: () => User | null;
35
74
  /**
@@ -45,27 +84,83 @@ declare const isAuthenticated: () => boolean;
45
84
  */
46
85
  declare const getIdentityConfig: () => IdentityConfig | null;
47
86
  /**
48
- * Fetches the GoTrue `/settings` endpoint.
49
- * Throws `MissingIdentityError` if Identity is not configured.
50
- * Throws `AuthError` if the endpoint is unreachable.
87
+ * Fetches your project's Identity settings (enabled providers, autoconfirm, signup disabled).
88
+ *
89
+ * @throws {MissingIdentityError} If Identity is not configured.
90
+ * @throws {AuthError} If the endpoint is unreachable.
51
91
  */
52
92
  declare const getSettings: () => Promise<Settings>;
53
93
 
54
- type AuthEvent = 'login' | 'logout' | 'token_refresh' | 'user_updated';
55
-
94
+ declare const AUTH_EVENTS: {
95
+ readonly LOGIN: "login";
96
+ readonly LOGOUT: "logout";
97
+ readonly TOKEN_REFRESH: "token_refresh";
98
+ readonly USER_UPDATED: "user_updated";
99
+ readonly RECOVERY: "recovery";
100
+ };
101
+ type AuthEvent = (typeof AUTH_EVENTS)[keyof typeof AUTH_EVENTS];
56
102
  type AuthCallback = (event: AuthEvent, user: User | null) => void;
57
103
  /**
58
- * Subscribes to auth state changes (login, logout, token refresh, user updates).
59
- * Returns an unsubscribe function. No-op on the server.
104
+ * Subscribes to auth state changes (login, logout, token refresh, user updates,
105
+ * and recovery). Returns an unsubscribe function. No-op on the server.
106
+ *
107
+ * The `'recovery'` event fires when {@link handleAuthCallback} processes a
108
+ * password recovery token. The user is logged in but has not yet set a new
109
+ * password. Redirect them to a password reset form and call
110
+ * `updateUser({ password })` to complete the flow.
60
111
  */
61
112
  declare const onAuthChange: (callback: AuthCallback) => (() => void);
62
- /** Logs in with email and password. Works in both browser and server contexts. */
113
+
114
+ /**
115
+ * Logs in with email and password. Works in both browser and server contexts.
116
+ *
117
+ * On success, sets `nf_jwt` and `nf_refresh` cookies and returns the authenticated {@link User}.
118
+ * In the browser, also emits a `'login'` event via {@link onAuthChange}.
119
+ *
120
+ * @throws {AuthError} On invalid credentials, network failure, or missing Netlify runtime.
121
+ *
122
+ * @remarks
123
+ * In Next.js server actions, call `redirect()` **after** `login()` returns, not inside a
124
+ * try/catch. Next.js implements `redirect()` by throwing a special error; wrapping it in
125
+ * try/catch will swallow the redirect.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * // Next.js server action
130
+ * const user = await login(email, password)
131
+ * redirect('/dashboard') // after login, not inside try/catch
132
+ * ```
133
+ */
63
134
  declare const login: (email: string, password: string) => Promise<User>;
64
- /** Creates a new account. Emits 'login' if autoconfirm is enabled. Works in both browser and server contexts. */
65
- declare const signup: (email: string, password: string, data?: Record<string, unknown>) => Promise<User>;
66
- /** Logs out the current user and clears the session. Works in both browser and server contexts. */
135
+ /**
136
+ * Creates a new account. Works in both browser and server contexts.
137
+ *
138
+ * If autoconfirm is enabled in your Identity settings, the user is logged in immediately:
139
+ * cookies are set and a `'login'` event is emitted. If autoconfirm is **disabled** (the default),
140
+ * the user receives a confirmation email and must click the link before they can log in.
141
+ * In that case, no cookies are set and no auth event is emitted.
142
+ *
143
+ * @throws {AuthError} On duplicate email, validation failure, network error, or missing Netlify runtime.
144
+ */
145
+ declare const signup: (email: string, password: string, data?: SignupData) => Promise<User>;
146
+ /**
147
+ * Logs out the current user and clears the session. Works in both browser and server contexts.
148
+ *
149
+ * Always deletes `nf_jwt` and `nf_refresh` cookies, even if the server-side token
150
+ * invalidation request fails. In the browser, emits a `'logout'` event via {@link onAuthChange}.
151
+ *
152
+ * @throws {AuthError} On missing Netlify runtime (server) or logout failure (browser).
153
+ */
67
154
  declare const logout: () => Promise<void>;
68
- /** Redirects to an OAuth provider. Always throws (the page navigates away). Browser only. */
155
+ /**
156
+ * Initiates an OAuth login by redirecting to the given provider (e.g., `'google'`, `'github'`).
157
+ * The page navigates away; this function never returns normally. Browser only.
158
+ *
159
+ * After the provider redirects back, call {@link handleAuthCallback} on page load
160
+ * to complete the login and obtain the {@link User}.
161
+ *
162
+ * @throws {AuthError} If called on the server.
163
+ */
69
164
  declare const oauthLogin: (provider: string) => never;
70
165
  interface CallbackResult {
71
166
  type: 'oauth' | 'confirmation' | 'recovery' | 'invite' | 'email_change';
@@ -76,8 +171,28 @@ interface CallbackResult {
76
171
  * Processes the URL hash after an OAuth redirect, email confirmation, password
77
172
  * recovery, invite acceptance, or email change. Call on page load. Browser only.
78
173
  * Returns `null` if the hash contains no auth parameters.
174
+ *
175
+ * Call this early in your app's initialization (e.g., in a layout component or
176
+ * root loader), **not** inside a route that requires authentication, because
177
+ * the callback URL must match the page where this function runs.
178
+ *
179
+ * For recovery callbacks (`result.type === 'recovery'`), the user is logged in
180
+ * but has **not** set a new password yet. Your app must check the result type
181
+ * and redirect to a password form that calls `updateUser({ password })`.
182
+ * A `'recovery'` event (not `'login'`) is emitted via {@link onAuthChange}.
183
+ *
184
+ * @throws {AuthError} If the callback token is invalid or the verification request fails.
79
185
  */
80
186
  declare const handleAuthCallback: () => Promise<CallbackResult | null>;
187
+ /**
188
+ * Hydrates the browser-side gotrue-js session from server-set auth cookies.
189
+ * Call this on page load when using server-side login to enable browser
190
+ * account operations (updateUser, verifyEmailChange, etc.).
191
+ *
192
+ * No-op if a browser session already exists or no auth cookies are present.
193
+ * No-op on the server.
194
+ */
195
+ declare const hydrateSession: () => Promise<User | null>;
81
196
 
82
197
  declare class AuthError extends Error {
83
198
  name: string;
@@ -92,32 +207,122 @@ declare class MissingIdentityError extends Error {
92
207
  constructor(message?: string);
93
208
  }
94
209
 
95
- /** Sends a password recovery email to the given address. */
210
+ /**
211
+ * Sends a password recovery email to the given address.
212
+ *
213
+ * @throws {AuthError} On network failure or if the request is rejected.
214
+ */
96
215
  declare const requestPasswordRecovery: (email: string) => Promise<void>;
97
- /** Redeems a recovery token and sets a new password. Logs the user in on success. */
216
+ /**
217
+ * Redeems a recovery token and sets a new password. Logs the user in on success.
218
+ *
219
+ * @throws {AuthError} If the token is invalid, expired, or the update fails.
220
+ */
98
221
  declare const recoverPassword: (token: string, newPassword: string) => Promise<User>;
99
- /** Confirms an email address using the token from a confirmation email. Logs the user in on success. */
222
+ /**
223
+ * Confirms an email address using the token from a confirmation email. Logs the user in on success.
224
+ *
225
+ * @throws {AuthError} If the token is invalid or expired.
226
+ */
100
227
  declare const confirmEmail: (token: string) => Promise<User>;
101
- /** Accepts an invite token and sets a password for the new account. Logs the user in on success. */
228
+ /**
229
+ * Accepts an invite token and sets a password for the new account. Logs the user in on success.
230
+ *
231
+ * @throws {AuthError} If the token is invalid or expired.
232
+ */
102
233
  declare const acceptInvite: (token: string, password: string) => Promise<User>;
103
- /** Verifies an email change using the token from a verification email. */
234
+ /**
235
+ * Verifies an email change using the token from a verification email.
236
+ * Auto-hydrates from auth cookies if no browser session exists. Browser only.
237
+ *
238
+ * @throws {AuthError} If called on the server, no user is logged in, or the token is invalid.
239
+ */
104
240
  declare const verifyEmailChange: (token: string) => Promise<User>;
105
- /** Updates the current user's metadata or credentials. Requires an active session. */
106
- declare const updateUser: (updates: Record<string, unknown>) => Promise<User>;
241
+ /**
242
+ * Updates the current user's email, password, or user metadata.
243
+ * Auto-hydrates from auth cookies if no browser session exists.
244
+ *
245
+ * @param updates - Fields to update. Pass `email` or `password` to change credentials,
246
+ * or `data` to update user metadata (e.g., `{ data: { full_name: 'New Name' } }`).
247
+ * @throws {AuthError} If no user is logged in or the update fails.
248
+ */
249
+ declare const updateUser: (updates: UserUpdates) => Promise<User>;
107
250
 
108
- declare const admin: {
251
+ /** The admin namespace for user management operations. */
252
+ interface Admin {
253
+ /**
254
+ * Lists all users. Works in both server and browser contexts.
255
+ *
256
+ * **Server:** calls GoTrue `GET /admin/users` with the operator token. Pagination
257
+ * options (`page`, `perPage`) are forwarded as query parameters.
258
+ *
259
+ * **Browser:** calls gotrue-js `user.admin.listUsers()`. The logged-in user must
260
+ * have an admin role. Pagination options are ignored (gotrue-js does not support them).
261
+ *
262
+ * @throws {AuthError} If the operator token is missing (server) or no admin user is logged in (browser).
263
+ */
109
264
  listUsers: (options?: {
110
265
  page?: number;
111
266
  perPage?: number;
112
267
  }) => Promise<User[]>;
268
+ /**
269
+ * Gets a single user by ID. Works in both server and browser contexts.
270
+ *
271
+ * **Server:** calls GoTrue `GET /admin/users/:id` with the operator token.
272
+ *
273
+ * **Browser:** calls gotrue-js `user.admin.getUser()`. The logged-in user must
274
+ * have an admin role.
275
+ *
276
+ * @throws {AuthError} If the user is not found, the operator token is missing (server),
277
+ * or no admin user is logged in (browser).
278
+ */
113
279
  getUser: (userId: string) => Promise<User>;
280
+ /**
281
+ * Creates a new user. The user is auto-confirmed (no confirmation email is sent).
282
+ * Works in both server and browser contexts.
283
+ *
284
+ * The optional `data` fields are spread as **top-level attributes** in the GoTrue
285
+ * request body (not nested under `user_metadata`). Use this to set `app_metadata`,
286
+ * `user_metadata`, `role`, or any other GoTrue user field at creation time.
287
+ *
288
+ * **Server:** calls GoTrue `POST /admin/users` with the operator token.
289
+ *
290
+ * **Browser:** calls gotrue-js `user.admin.createUser()`. The logged-in user must
291
+ * have an admin role.
292
+ *
293
+ * @throws {AuthError} If the email already exists, the operator token is missing (server),
294
+ * or no admin user is logged in (browser).
295
+ */
114
296
  createUser: (params: {
115
297
  email: string;
116
298
  password: string;
117
299
  data?: Record<string, unknown>;
118
300
  }) => Promise<User>;
119
- updateUser: (userId: string, attributes: Record<string, unknown>) => Promise<User>;
301
+ /**
302
+ * Updates an existing user by ID. Works in both server and browser contexts.
303
+ *
304
+ * **Server:** calls GoTrue `PUT /admin/users/:id` with the operator token.
305
+ *
306
+ * **Browser:** calls gotrue-js `user.admin.updateUser()`. The logged-in user must
307
+ * have an admin role.
308
+ *
309
+ * @throws {AuthError} If the user is not found, the update fails, the operator token
310
+ * is missing (server), or no admin user is logged in (browser).
311
+ */
312
+ updateUser: (userId: string, attributes: AdminUserUpdates) => Promise<User>;
313
+ /**
314
+ * Deletes a user by ID. Works in both server and browser contexts.
315
+ *
316
+ * **Server:** calls GoTrue `DELETE /admin/users/:id` with the operator token.
317
+ *
318
+ * **Browser:** calls gotrue-js `user.admin.deleteUser()`. The logged-in user must
319
+ * have an admin role.
320
+ *
321
+ * @throws {AuthError} If the user is not found, the deletion fails, the operator token
322
+ * is missing (server), or no admin user is logged in (browser).
323
+ */
120
324
  deleteUser: (userId: string) => Promise<void>;
121
- };
325
+ }
326
+ declare const admin: Admin;
122
327
 
123
- export { type AppMetadata, type AuthCallback, AuthError, type AuthEvent, type AuthProvider, type CallbackResult, type IdentityConfig, MissingIdentityError, type Settings, type User, acceptInvite, admin, confirmEmail, getIdentityConfig, getSettings, getUser, handleAuthCallback, isAuthenticated, login, logout, oauthLogin, onAuthChange, recoverPassword, requestPasswordRecovery, signup, updateUser, verifyEmailChange };
328
+ export { AUTH_EVENTS, type AdminUserUpdates, type AppMetadata, type AuthCallback, AuthError, type AuthEvent, type AuthProvider, type CallbackResult, type IdentityConfig, MissingIdentityError, type Settings, type SignupData, type User, type UserUpdates, acceptInvite, admin, confirmEmail, getIdentityConfig, getSettings, getUser, handleAuthCallback, hydrateSession, isAuthenticated, login, logout, oauthLogin, onAuthChange, recoverPassword, requestPasswordRecovery, signup, updateUser, verifyEmailChange };