← NetlifyCONTENT HISTORY

Update to Netlify

Snapshot Nov 19, 2026 · 00:11 UTC · version 1.9.0

Collection source: downloaded plugin package.

WHAT CHANGED

Instructions updated for netlify-identity

Full description — Now says: @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity...

Observed in instructions or declared skills. Runtime behavior has not been tested.

Save Netlify and check future changes in Following.

Up to 3 plugins free · no card required.

All fields and original values.

Full description

Before

Oct 7, 2026 · 00:02 UTC

@netlify/identity — signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating conte...

After

Nov 19, 2026 · 00:11 UTC

@netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gati...

Skill instructions

Before

Oct 7, 2026 · 00:02 UTC

@netlify/identity — signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating conte...

After

Nov 19, 2026 · 00:11 UTC

@netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gati...

Compare saved observations

Download comparison JSON

SKILL.md text changes

− removed · + added

--- before
+++ after
@@ -1,11 +1,11 @@
 ---
 name: netlify-identity
-description: Add user authentication to a Netlify site with @netlify/identity — signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, "auth middleware" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.
+description: Add user authentication to a Netlify site with @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, "auth middleware" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, accepting user invites, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.
 ---
 
 # Netlify Identity
 
-Use `@netlify/identity` (npm). For new projects it replaces the legacy `netlify-identity-widget` and `gotrue-js` — do not reach for those.
+Use `@netlify/identity` (npm). For new projects it replaces the legacy `netlify-identity-widget` and `gotrue-js`. Do not reach for those.
 
 ```bash
 npm install @netlify/identity
@@ -13,11 +13,11 @@
 
 Framework examples (Next.js/Astro/Remix/SvelteKit) and the full API reference are in the [`@netlify/identity` README on npm](https://www.npmjs.com/package/@netlify/identity).
 
-> **Identity does not run under `netlify dev`.** Test all auth flows on a deploy — Deploy Previews work. Local dev will not complete signup/login/OAuth.
+> **Identity does not run under `netlify dev`.** Test all auth flows on a deploy. Deploy Previews work. Local dev will not complete signup/login/OAuth.
 
-> **Identity config is dashboard-only — there is no public API.** Never curl `api.netlify.com` to flip or read Identity settings, never read tokens from local Netlify config, never probe undocumented endpoints. Enable and configure Identity at `https://app.netlify.com/projects/{site_name}/identity`.
+> **Identity config is dashboard-only. There is no public API.** Never curl `api.netlify.com` to flip or read Identity settings, never read tokens from local Netlify config, and never probe undocumented endpoints. Enable and configure Identity at `https://app.netlify.com/projects/{site_name}/identity`.
 
-> **Never build a from-scratch OAuth flow alongside Identity.** No provider app registration in code, no `client_id`/`secret` in source, no custom callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`. Raw OAuth beside Identity is the most common source of rework.
+> **Never build a from-scratch OAuth flow alongside Identity.** No provider app registration in code, no `client_id`/`secret` in source, and no custom callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`. Raw OAuth beside Identity is the most common source of rework.
 
 ## Client auth (browser)
 
@@ -40,16 +40,26 @@
 oauthLogin('github')
 ```
 
-> **`handleAuthCallback()` is mandatory on your landing page.** Without it, OAuth redirects, email-confirmation links, password-recovery links, and invite links never complete. Call it on page load:
+> **`handleAuthCallback()` is mandatory on your landing page.** Without it, OAuth redirects, email-confirmation links, password-recovery links, and invite links never complete. Call it on page load.
+
+> **Invites are NOT logged in by `handleAuthCallback()`.** For an invite it returns `type === 'invite'` with the token in `result.token` and `result.user === null`. The account does not exist yet. You must collect a password and call `acceptInvite(result.token, password)`. If you skip this step, invited users never get an account.
 
 ```ts
-import { handleAuthCallback } from '@netlify/identity'
+import { handleAuthCallback, acceptInvite } from '@netlify/identity'
 
 const result = await handleAuthCallback() // falsy if no token in URL hash
-if (result) console.log(result.type, result.user.email) // confirmation | invite | recovery | email change
+if (result?.type === 'invite' && result.token) {
+  // Invited user has no account yet. Ask them to choose a password first.
+  const password = (document.getElementById('password') as HTMLInputElement).value
+  const user = await acceptInvite(result.token, password)
+  console.log('Account created:', user.email)
+} else if (result) {
+  // OAuth, email confirmation, recovery, or email change
+  console.log(result.type, result.user?.email)
+}
 ```
 
-Alternatives for a single token type: `recoverPassword()` (recovery), `acceptInvite()` (invite). Refresh a session with `refreshSession()`.
+For recovery tokens you can call `recoverPassword()` directly instead. Refresh a session with `refreshSession()`.
 
 Don't hard-code which providers exist. Call `getSettings()` at startup and render the signup form and OAuth buttons from what it returns.
 
@@ -57,7 +67,7 @@
 
 Server-side `getUser()`/`login()`/`admin.*` require modern **v2 functions** (`export default`). The v1 `export { handler }` form is not supported.
 
-`getUser()` works in both runtimes. **`admin.*` runs ONLY in Netlify Functions — not the browser, not Edge Functions.**
+`getUser()` works in both runtimes. **`admin.*` runs ONLY in Netlify Functions. It does not run in the browser or in Edge Functions.**
 
 ```ts
 // netlify/functions/me.ts — verify user
@@ -71,7 +81,7 @@
 }
 ```
 
-Edge Function form is identical but imports `Context` from `@netlify/edge-functions`.
+The Edge Function form is identical but imports `Context` from `@netlify/edge-functions`.
 
 ### Role checks
 
@@ -110,7 +120,7 @@
 
 The platform calls your handler when an Identity event occurs. Export a default object with a method per event. File: `netlify/functions/identity.mts`.
 
-> Typed handlers (`UserSignupEvent`, `event.deny()`) require `@netlify/functions` ≥ 5.2.0. Older installs must use the legacy filename convention (`identity-signup.ts`, etc.) — see `references/authorization-and-sessions.md`.
+> Typed handlers (`UserSignupEvent`, `event.deny()`) require `@netlify/functions` ≥ 5.2.0. Older installs must use the legacy filename convention (`identity-signup.ts`, etc.). See `references/authorization-and-sessions.md`.
 
 | Handler | Fires when |
 |---|---|
@@ -144,24 +154,24 @@
 }
 ```
 
-- `event.deny()` — rejects the action; end user gets `401`, no observability error. First handler to call it aborts the chain; later subscribers are not invoked. (Legacy filename functions signal denial with a non-2xx `Response` instead.)
-- Return `{ user: {...} }` to modify the record before persistence (canonical way to set roles at signup). Roles ride in the JWT, so a role change takes effect on the user's **next login or token refresh, not immediately** — see Roles & the JWT below.
-- Background mode: `export const config: Config = { background: true }` — action completes immediately, handler runs async.
+- `event.deny()` rejects the action. The end user gets a `401`, and no error appears in observability. The first handler to call it aborts the chain, and later subscribers are not invoked. Legacy filename functions signal denial with a non-2xx `Response` instead.
+- Return `{ user: {...} }` to modify the record before it is persisted. This is the canonical way to set roles at signup. Roles ride in the JWT, so a role change takes effect on the user's **next login or token refresh, not immediately**. See Roles & the JWT below.
+- Background mode: `export const config: Config = { background: true }`. The action completes immediately and the handler runs asynchronously.
 
 ## Roles & the JWT
 
-- `user.roles` is read from `app_metadata.roles`, carried in the JWT (cookie `nf_jwt`; refresh via `nf_refresh`).
-- `user_metadata` — user-editable profile (`full_name`, `email`). `app_metadata` — app data incl. `roles`, not user-editable.
+- `user.roles` is read from `app_metadata.roles` and carried in the JWT (cookie `nf_jwt`; refresh via `nf_refresh`).
+- `user_metadata` holds the user-editable profile (`full_name`, `email`). `app_metadata` holds app data, including `roles`, and is not user-editable.
 
-> **Role changes are NOT immediate.** They take effect on next login or token refresh. Changing roles does not invalidate the current JWT. Force it with `refreshSession()`.
+> **Role changes are NOT immediate.** They take effect on next login or token refresh. Changing roles does not invalidate the current JWT. Force a refresh with `refreshSession()`.
 
-Set roles for existing users via `admin.updateUser()` in a Netlify Function; at signup via the `userSignup` event handler above.
+Set roles for existing users via `admin.updateUser()` in a Netlify Function. Set them at signup via the `userSignup` event handler above.
 
 Deep guides for SSR/session hydration and authorization live in `references/advanced-patterns.md` and `references/authorization-and-sessions.md`.
 
 ## CDN-edge RBAC (redirect rules)
 
-Enforced at the edge with no origin round trip. A mismatched role gets a 404 unless you add a fallback — **always pair a role-gated rule with a fallback.**
+Enforced at the edge with no origin round trip. A mismatched role gets a 404 unless you add a fallback. **Always pair a role-gated rule with a fallback.**
 
 `_redirects`:
 ```
@@ -181,21 +191,21 @@
   conditions = {Role = ["editor", "admin"]}
 ```
 
-Use redirect rules for path-based gating; use function-based `user.roles` checks for custom authorization logic.
+Use redirect rules for path-based gating. Use function-based `user.roles` checks for custom authorization logic.
 
 ## Configuration (dashboard-only)
 
-Base: `https://app.netlify.com/projects/{site_name}/identity`. Enable with **Enable Identity**. Identity requires HTTPS — set up SSL before integrating on a custom domain.
+Base: `https://app.netlify.com/projects/{site_name}/identity`. Enable with **Enable Identity**. Identity requires HTTPS, so set up SSL before integrating on a custom domain.
 
-- **Registration** (`?tab=registration#registration-preferences`): **Open** (default, anyone can sign up) or **Invite only** (all users, including external-provider logins, must be invited first).
+- **Registration** (`?tab=registration#registration-preferences`): **Open** (default; anyone can sign up) or **Invite only** (all users, including external-provider logins, must be invited first).
 - **Confirmation / autoconfirm** (`?tab=emails#confirmation-template`): check the box to skip email verification.
-- **External providers** (`?tab=registration#external-providers`): Google/GitHub/GitLab/Bitbucket. For branded OAuth (your app name instead of "Netlify Identity"), register your app with the provider, get client ID + secret, and enter them **in the Netlify settings UI** — not in code.
-- **Invitations** (`?tab=users`): enter addresses to send invites; link carries `invite_token`.
-- **Password recovery**: user page → **Send reset password email**; link carries `recovery_token`.
+- **External providers** (`?tab=registration#external-providers`): Google/GitHub/GitLab/Bitbucket. For branded OAuth (your app name instead of "Netlify Identity"), register your app with the provider, get a client ID and secret, and enter them **in the Netlify settings UI**, not in code.
+- **Invitations** (`?tab=users`): enter addresses to send invites. The link carries `invite_token`. Complete it with `handleAuthCallback()` + `acceptInvite(token, password)` as shown above.
+- **Password recovery**: on the user page, use **Send reset password email**. The link carries `recovery_token`.
 
 ### Emails (Pro plans or higher)
 
-Default sender is `no-reply@netlify.com`. Custom SMTP sender and custom templates both require **Pro plans or higher**.
+The default sender is `no-reply@netlify.com`. A custom SMTP sender and custom templates both require **Pro plans or higher**.
 
 Template variables (Go syntax): `{{ .Email }}`, `{{ .NewEmail }}` (email-change only), `{{ .SiteURL }}`, `{{ .ConfirmationURL }}`, `{{ .Token }}`.
 
@@ -207,27 +217,40 @@
 {{ .SiteURL }}/path/#email_change_token={{ .Token }}
 ```
 
-Custom template constraints: inline CSS only; absolute image links; **no `<html>`/`<head>`/`<body>` tags**; ensure your build doesn't alter Go template variables.
+Custom template constraints:
+- Inline CSS only.
+- Absolute image links.
+- **No `<html>`/`<head>`/`<body>` tags.**
+- Ensure your build doesn't alter Go template variables.
 
 ### Audit log (Pro plans or higher)
 
-`?tab=audit-log`. Search with a scoped term: `author:[string]` or `action:[string]`. Action names: `login`, `logout`, `user_signedup`, `user_deleted`, `user_modified`, `token_revoked`, `token_refreshed`, `user_recovery_requested`, `user_invited`.
+`?tab=audit-log`. Search with a scoped term: `author:[string]` or `action:[string]`.
+
+Action names: `login`, `logout`, `user_signedup`, `user_deleted`, `user_modified`, `token_revoked`, `token_refreshed`, `user_recovery_requested`, `user_invited`.
 
 ## External JWT providers (Enterprise)
 
-Available on **Enterprise plans**. You may use Netlify Identity OR an external JWT provider — **not both at once**; you cannot authenticate third-party JWTs while Netlify Identity is enabled.
+Available on **Enterprise plans**. You may use Netlify Identity OR an external JWT provider, **not both at once**. You cannot authenticate third-party JWTs while Netlify Identity is enabled.
 
-- Roles path: Netlify Identity `app_metadata.roles`; external provider `app_metadata.authorization.roles`. Custom path → contact support.
-- JWT header must be `{"alg": "HS256", "typ": "JWT"}` (HS256 required). Payload `exp` is required and must be a future Unix Epoch time.
-- Set the JWT secret at `Project configuration > General > Visitor access > JWT secret`. Project-level overrides team-level defaults.
+- Roles path: Netlify Identity uses `app_metadata.roles`; an external provider uses `app_metadata.authorization.roles`. For a custom path, contact support.
+- The JWT header must be `{"alg": "HS256", "typ": "JWT"}` (HS256 required). The payload `exp` is required and must be a future Unix Epoch time.
+- Set the JWT secret at `Project configuration > General > Visitor access > JWT secret`. Project-level settings override team-level defaults.
 
 ## On failure — stop, don't guess
 
-If callbacks 404, `/.netlify/identity/*` is unreachable, or an OAuth flow never returns: surface the error, the dashboard URL (`https://app.netlify.com/projects/{site_name}/identity`), and the setting to check (registration preference, external provider config, confirmation/autoconfirm). Then stop. Do not invent recovery commands. Remember: Identity does not work under `netlify dev` — confirm you are testing on a deploy.
+If callbacks 404, `/.netlify/identity/*` is unreachable, or an OAuth flow never returns:
+1. Surface the error.
+2. Give the dashboard URL (`https://app.netlify.com/projects/{site_name}/identity`).
+3. Name the setting to check (registration preference, external provider config, confirmation/autoconfirm).
+4. Then stop. Do not invent recovery commands.
+
+Remember: Identity does not work under `netlify dev`. Confirm you are testing on a deploy.
 
-Site-gating requests ("lock this site to my company", employees-only) route to the netlify-access-control skill first — Identity is the app-level user layer only.
+Site-gating requests ("lock this site to my company", employees-only) route to the netlify-access-control skill first. Identity is the app-level user layer only. Restricting who can view the whole project uses [project visibility](https://docs.netlify.com/manage/security/secure-access-to-sites/project-visibility) or [Password Protection](https://docs.netlify.com/manage/security/secure-access-to-sites/password-protection), not Identity.
 
-<!-- gap: getSettings() is referenced by house rules for provider discovery but its signature/return shape is not documented in the intermediate. -->
+<!-- gap: getSettings() signature/return shape is not documented in the intermediate. -->
+<!-- gap: handleAuthCallback() result.type strings other than 'invite' are not enumerated. -->
 
 <!-- system: agent-context/identity/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->
 # Netlify house rules (identity)
@@ -265,3 +288,10 @@
    sets the role, not only in a separate JWT section: an agent answering a
    signup question reads the signup example and stops, and it has shipped
    answers that omit the delay.
+10. Before setting up Identity for an internal tool, ask who signs in. If
+    they can already pass the project's Netlify login (a private project or
+    team login protection), the app has a verified user without Identity:
+    read `context.user` in functions and edge functions and skip the second
+    login. Identity is for users outside that Netlify login. The two never
+    merge: `context.user` has no roles or `app_metadata`, and `getUser()`
+    never returns it.
Full technical diff · 2 changed fields

changed /description

BEFORE
"Add user authentication to a Netlify site with @netlify/identity — signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead."
AFTER
"Add user authentication to a Netlify site with @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, accepting user invites, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead."

changed /skill_md_contents

BEFORE
"---\nname: netlify-identity\ndescription: Add user authentication to a Netlify site with @netlify/identity — signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.\n---\n\n# Netlify Identity\n\nUse `@netlify/identity` (npm). For new projects it replaces the legacy `netlify-identity-widget` and `gotrue-js` — do not reach for those.\n\n```bash\nnpm install @netlify/identity\n```\n\nFramework examples (Next.js/Astro/Remix/SvelteKit) and the full API reference are in the [`@netlify/identity` README on npm](https://www.npmjs.com/package/@netlify/identity).\n\n> **Identity does not run under `netlify dev`.** Test all auth flows on a deploy — Deploy Previews work. Local dev will not complete signup/login/OAuth.\n\n> **Identity config is dashboard-only — there is no public API.** Never curl `api.netlify.com` to flip or read Identity settings, never read tokens from local Netlify config, never probe undocumented endpoints. Enable and configure Identity at `https://app.netlify.com/projects/{site_name}/identity`.\n\n> **Never build a from-scratch OAuth flow alongside Identity.** No provider app registration in code, no `client_id`/`secret` in source, no custom callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`. Raw OAuth beside Identity is the most common source of rework.\n\n## Client auth (browser)\n\n```ts\nimport { signup, login, logout, getUser, oauthLogin, handleAuthCallback } from '@netlify/identity'\n\n// Register — confirmation email sent by default (unless autoconfirm is on)\nconst user = await signup('jane@example.com', 'securepassword', { full_name: 'Jane Doe' })\n\n// Log in / out\nawait login('jane@example.com', 'securepassword')\nawait logout()\n\n// Current user or null\nconst current = await getUser()\nif (current) console.log(`Logged in as ${current.email}`)\n\n// External provider — redirects the browser; provider is one of\n// 'google' | 'github' | 'gitlab' | 'bitbucket'\noauthLogin('github')\n```\n\n> **`handleAuthCallback()` is mandatory on your landing page.** Without it, OAuth redirects, email-confirmation links, password-recovery links, and invite links never complete. Call it on page load:\n\n```ts\nimport { handleAuthCallback } from '@netlify/identity'\n\nconst result = await handleAuthCallback() // falsy if no token in URL hash\nif (result) console.log(result.type, result.user.email) // confirmation | invite | recovery | email change\n```\n\nAlternatives for a single token type: `recoverPassword()` (recovery), `acceptInvite()` (invite). Refresh a session with `refreshSession()`.\n\nDon't hard-code which providers exist. Call `getSettings()` at startup and render the signup form and OAuth buttons from what it returns.\n\n## Server-side auth (Netlify Functions & Edge Functions)\n\nServer-side `getUser()`/`login()`/`admin.*` require modern **v2 functions** (`export default`). The v1 `export { handler }` form is not supported.\n\n`getUser()` works in both runtimes. **`admin.*` runs ONLY in Netlify Functions — not the browser, not Edge Functions.**\n\n```ts\n// netlify/functions/me.ts — verify user\nimport { getUser } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  return Response.json({ id: user.id, email: user.email })\n}\n```\n\nEdge Function form is identical but imports `Context` from `@netlify/edge-functions`.\n\n### Role checks\n\n```ts\n// netlify/functions/admin-users.ts\nimport { getUser, admin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  if (!user.roles.includes('admin')) return new Response('Forbidden', { status: 403 })\n  const users = await admin.listUsers()\n  return Response.json({ users })\n}\n```\n\n### CSRF: required for server-side auth endpoints\n\n> Any endpoint that runs `login()`, `signup()`, or `logout()` server-side **must** call `verifyRequestOrigin(req)` at the top of the handler. It throws a 403 on origin mismatch.\n\n```ts\n// netlify/functions/login.ts\nimport { login, verifyRequestOrigin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  verifyRequestOrigin(req)\n  const { email, password } = await req.json()\n  await login(email, password)\n  return new Response(null, { status: 302, headers: { Location: '/dashboard' } })\n}\n```\n\n## Identity event functions\n\nThe platform calls your handler when an Identity event occurs. Export a default object with a method per event. File: `netlify/functions/identity.mts`.\n\n> Typed handlers (`UserSignupEvent`, `event.deny()`) require `@netlify/functions` ≥ 5.2.0. Older installs must use the legacy filename convention (`identity-signup.ts`, etc.) — see `references/authorization-and-sessions.md`.\n\n| Handler | Fires when |\n|---|---|\n| `userValidate` | Signup attempt, before account creation. Block bad signups here. |\n| `userSignup` | Signup completes (after email confirmation if enabled). Assign roles, sync, welcome. |\n| `userLogin` | User logs in. Track/last-seen/block. |\n| `userModified` | Profile updated. |\n| `userDeleted` | User deleted (notification only). |\n\nEvent `user` fields are camelCase (`appMetadata`, `userMetadata`, `confirmedAt`).\n\n```typescript\n// netlify/functions/identity.mts — deny a signup\nimport type { UserValidateEvent } from \"@netlify/functions\"\n\nexport default {\n  userValidate(event: UserValidateEvent) {\n    if (!event.user.email?.endsWith(\"@example.com\")) return event.deny()\n  },\n}\n```\n\n```typescript\n// netlify/functions/identity.mts — assign roles at signup\nimport type { UserSignupEvent } from \"@netlify/functions\"\n\nexport default {\n  userSignup(event: UserSignupEvent) {\n    return { user: { ...event.user, appMetadata: { ...event.user.appMetadata, roles: [\"member\"] } } }\n  },\n}\n```\n\n- `event.deny()` — rejects the action; end user gets `401`, no observability error. First handler to call it aborts the chain; later subscribers are not invoked. (Legacy filename functions signal denial with a non-2xx `Response` instead.)\n- Return `{ user: {...} }` to modify the record before persistence (canonical way to set roles at signup). Roles ride in the JWT, so a role change takes effect on the user's **next login or token refresh, not immediately** — see Roles & the JWT below.\n- Background mode: `export const config: Config = { background: true }` — action completes immediately, handler runs async.\n\n## Roles & the JWT\n\n- `user.roles` is read from `app_metadata.roles`, carried in the JWT (cookie `nf_jwt`; refresh via `nf_refresh`).\n- `user_metadata` — user-editable profile (`full_name`, `email`). `app_metadata` — app data incl. `roles`, not user-editable.\n\n> **Role changes are NOT immediate.** They take effect on next login or token refresh. Changing roles does not invalidate the current JWT. Force it with `refreshSession()`.\n\nSet roles for existing users via `admin.updateUser()` in a Netlify Function; at signup via the `userSignup` event handler above.\n\nDeep guides for SSR/session hydration and authorization live in `references/advanced-patterns.md` and `references/authorization-and-sessions.md`.\n\n## CDN-edge RBAC (redirect rules)\n\nEnforced at the edge with no origin round trip. A mismatched role gets a 404 unless you add a fallback — **always pair a role-gated rule with a fallback.**\n\n`_redirects`:\n```\n/admin/*  /admin/:splat  200!  Role=admin\n/admin/*  /login         401!\n# Multiple roles chained with commas:\n/private/* /private/:splat 200! Role=editor,admin\n```\n\n`netlify.toml`:\n```toml\n[[redirects]]\n  from = \"/admin/*\"\n  to = \"/admin/:splat\"\n  force = true\n  status = 200\n  conditions = {Role = [\"editor\", \"admin\"]}\n```\n\nUse redirect rules for path-based gating; use function-based `user.roles` checks for custom authorization logic.\n\n## Configuration (dashboard-only)\n\nBase: `https://app.netlify.com/projects/{site_name}/identity`. Enable with **Enable Identity**. Identity requires HTTPS — set up SSL before integrating on a custom domain.\n\n- **Registration** (`?tab=registration#registration-preferences`): **Open** (default, anyone can sign up) or **Invite only** (all users, including external-provider logins, must be invited first).\n- **Confirmation / autoconfirm** (`?tab=emails#confirmation-template`): check the box to skip email verification.\n- **External providers** (`?tab=registration#external-providers`): Google/GitHub/GitLab/Bitbucket. For branded OAuth (your app name instead of \"Netlify Identity\"), register your app with the provider, get client ID + secret, and enter them **in the Netlify settings UI** — not in code.\n- **Invitations** (`?tab=users`): enter addresses to send invites; link carries `invite_token`.\n- **Password recovery**: user page → **Send reset password email**; link carries `recovery_token`.\n\n### Emails (Pro plans or higher)\n\nDefault sender is `no-reply@netlify.com`. Custom SMTP sender and custom templates both require **Pro plans or higher**.\n\nTemplate variables (Go syntax): `{{ .Email }}`, `{{ .NewEmail }}` (email-change only), `{{ .SiteURL }}`, `{{ .ConfirmationURL }}`, `{{ .Token }}`.\n\nCustom-link hash fragments per action:\n```\n{{ .SiteURL }}/path/#invite_token={{ .Token }}\n{{ .SiteURL }}/path/#confirmation_token={{ .Token }}\n{{ .SiteURL }}/path/#recovery_token={{ .Token }}\n{{ .SiteURL }}/path/#email_change_token={{ .Token }}\n```\n\nCustom template constraints: inline CSS only; absolute image links; **no `<html>`/`<head>`/`<body>` tags**; ensure your build doesn't alter Go template variables.\n\n### Audit log (Pro plans or higher)\n\n`?tab=audit-log`. Search with a scoped term: `author:[string]` or `action:[string]`. Action names: `login`, `logout`, `user_signedup`, `user_deleted`, `user_modified`, `token_revoked`, `token_refreshed`, `user_recovery_requested`, `user_invited`.\n\n## External JWT providers (Enterprise)\n\nAvailable on **Enterprise plans**. You may use Netlify Identity OR an external JWT provider — **not both at once**; you cannot authenticate third-party JWTs while Netlify Identity is enabled.\n\n- Roles path: Netlify Identity `app_metadata.roles`; external provider `app_metadata.authorization.roles`. Custom path → contact support.\n- JWT header must be `{\"alg\": \"HS256\", \"typ\": \"JWT\"}` (HS256 required). Payload `exp` is required and must be a future Unix Epoch time.\n- Set the JWT secret at `Project configuration > General > Visitor access > JWT secret`. Project-level overrides team-level defaults.\n\n## On failure — stop, don't guess\n\nIf callbacks 404, `/.netlify/identity/*` is unreachable, or an OAuth flow never returns: surface the error, the dashboard URL (`https://app.netlify.com/projects/{site_name}/identity`), and the setting to check (registration preference, external provider config, confirmation/autoconfirm). Then stop. Do not invent recovery commands. Remember: Identity does not work under `netlify dev` — confirm you are testing on a deploy.\n\nSite-gating requests (\"lock this site to my company\", employees-only) route to the netlify-access-control skill first — Identity is the app-level user layer only.\n\n<!-- gap: getSettings() is referenced by house rules for provider discovery but its signature/return shape is not documented in the intermediate. -->\n\n<!-- system: agent-context/identity/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (identity)\n\nThese are org conventions, not docs facts — merged into the rendered skill by\nctx-gen and never generated. Owned by the skills maintainer.\n\n1. Deep guides live in this skill: `references/advanced-patterns.md`\n   (SSR/session hydration) and `references/authorization-and-sessions.md`.\n2. Identity does not work under `netlify dev` — test auth flows on deploys\n   (Deploy Previews work).\n3. Identity configuration has no public API — it is dashboard-only. Never curl\n   `api.netlify.com` to flip or inspect Identity settings, never read auth\n   tokens from `~/Library/Preferences/netlify/config.json`, never probe for\n   undocumented endpoints.\n4. On failure (callback 404s, `/.netlify/identity/*` unreachable, OAuth flow\n   doesn't return), surface the error, the dashboard URL, and the setting to\n   check — then stop. Do not invent recovery commands.\n5. Never build a from-scratch third-party OAuth flow when Identity is in play —\n   no provider app registration, no `client_id`/`secret` in code, no custom\n   callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`;\n   raw OAuth beside Identity is the single most common source of rework.\n6. Server-side `getUser()`/`login()`/`admin.*` require modern v2 functions\n   (`export default`) — v1 `export { handler }` is not supported. Typed\n   Identity event handlers (`UserSignupEvent`, `event.deny()`) require\n   `@netlify/functions` ≥ 5.2.0; older installs use the legacy filenames.\n7. Don't hard-code which auth providers exist — call `getSettings()` at\n   startup and render the signup form and OAuth buttons from what it returns.\n8. Site-gating requests (\"lock this site to my company\", employees-only)\n   route to the netlify-access-control skill first — Identity is the\n   app-level user layer only.\n9. Any answer that assigns or changes roles — at signup, via `admin.*`, or in\n   the dashboard — must say the change takes effect on the user's next login\n   or token refresh, not immediately. Keep that sentence next to the code that\n   sets the role, not only in a separate JWT section: an agent answering a\n   signup question reads the signup example and stops, and it has shipped\n   answers that omit the delay.\n"
AFTER
"---\nname: netlify-identity\ndescription: Add user authentication to a Netlify site with @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, accepting user invites, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.\n---\n\n# Netlify Identity\n\nUse `@netlify/identity` (npm). For new projects it replaces the legacy `netlify-identity-widget` and `gotrue-js`. Do not reach for those.\n\n```bash\nnpm install @netlify/identity\n```\n\nFramework examples (Next.js/Astro/Remix/SvelteKit) and the full API reference are in the [`@netlify/identity` README on npm](https://www.npmjs.com/package/@netlify/identity).\n\n> **Identity does not run under `netlify dev`.** Test all auth flows on a deploy. Deploy Previews work. Local dev will not complete signup/login/OAuth.\n\n> **Identity config is dashboard-only. There is no public API.** Never curl `api.netlify.com` to flip or read Identity settings, never read tokens from local Netlify config, and never probe undocumented endpoints. Enable and configure Identity at `https://app.netlify.com/projects/{site_name}/identity`.\n\n> **Never build a from-scratch OAuth flow alongside Identity.** No provider app registration in code, no `client_id`/`secret` in source, and no custom callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`. Raw OAuth beside Identity is the most common source of rework.\n\n## Client auth (browser)\n\n```ts\nimport { signup, login, logout, getUser, oauthLogin, handleAuthCallback } from '@netlify/identity'\n\n// Register — confirmation email sent by default (unless autoconfirm is on)\nconst user = await signup('jane@example.com', 'securepassword', { full_name: 'Jane Doe' })\n\n// Log in / out\nawait login('jane@example.com', 'securepassword')\nawait logout()\n\n// Current user or null\nconst current = await getUser()\nif (current) console.log(`Logged in as ${current.email}`)\n\n// External provider — redirects the browser; provider is one of\n// 'google' | 'github' | 'gitlab' | 'bitbucket'\noauthLogin('github')\n```\n\n> **`handleAuthCallback()` is mandatory on your landing page.** Without it, OAuth redirects, email-confirmation links, password-recovery links, and invite links never complete. Call it on page load.\n\n> **Invites are NOT logged in by `handleAuthCallback()`.** For an invite it returns `type === 'invite'` with the token in `result.token` and `result.user === null`. The account does not exist yet. You must collect a password and call `acceptInvite(result.token, password)`. If you skip this step, invited users never get an account.\n\n```ts\nimport { handleAuthCallback, acceptInvite } from '@netlify/identity'\n\nconst result = await handleAuthCallback() // falsy if no token in URL hash\nif (result?.type === 'invite' && result.token) {\n  // Invited user has no account yet. Ask them to choose a password first.\n  const password = (document.getElementById('password') as HTMLInputElement).value\n  const user = await acceptInvite(result.token, password)\n  console.log('Account created:', user.email)\n} else if (result) {\n  // OAuth, email confirmation, recovery, or email change\n  console.log(result.type, result.user?.email)\n}\n```\n\nFor recovery tokens you can call `recoverPassword()` directly instead. Refresh a session with `refreshSession()`.\n\nDon't hard-code which providers exist. Call `getSettings()` at startup and render the signup form and OAuth buttons from what it returns.\n\n## Server-side auth (Netlify Functions & Edge Functions)\n\nServer-side `getUser()`/`login()`/`admin.*` require modern **v2 functions** (`export default`). The v1 `export { handler }` form is not supported.\n\n`getUser()` works in both runtimes. **`admin.*` runs ONLY in Netlify Functions. It does not run in the browser or in Edge Functions.**\n\n```ts\n// netlify/functions/me.ts — verify user\nimport { getUser } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  return Response.json({ id: user.id, email: user.email })\n}\n```\n\nThe Edge Function form is identical but imports `Context` from `@netlify/edge-functions`.\n\n### Role checks\n\n```ts\n// netlify/functions/admin-users.ts\nimport { getUser, admin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  if (!user.roles.includes('admin')) return new Response('Forbidden', { status: 403 })\n  const users = await admin.listUsers()\n  return Response.json({ users })\n}\n```\n\n### CSRF: required for server-side auth endpoints\n\n> Any endpoint that runs `login()`, `signup()`, or `logout()` server-side **must** call `verifyRequestOrigin(req)` at the top of the handler. It throws a 403 on origin mismatch.\n\n```ts\n// netlify/functions/login.ts\nimport { login, verifyRequestOrigin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  verifyRequestOrigin(req)\n  const { email, password } = await req.json()\n  await login(email, password)\n  return new Response(null, { status: 302, headers: { Location: '/dashboard' } })\n}\n```\n\n## Identity event functions\n\nThe platform calls your handler when an Identity event occurs. Export a default object with a method per event. File: `netlify/functions/identity.mts`.\n\n> Typed handlers (`UserSignupEvent`, `event.deny()`) require `@netlify/functions` ≥ 5.2.0. Older installs must use the legacy filename convention (`identity-signup.ts`, etc.). See `references/authorization-and-sessions.md`.\n\n| Handler | Fires when |\n|---|---|\n| `userValidate` | Signup attempt, before account creation. Block bad signups here. |\n| `userSignup` | Signup completes (after email confirmation if enabled). Assign roles, sync, welcome. |\n| `userLogin` | User logs in. Track/last-seen/block. |\n| `userModified` | Profile updated. |\n| `userDeleted` | User deleted (notification only). |\n\nEvent `user` fields are camelCase (`appMetadata`, `userMetadata`, `confirmedAt`).\n\n```typescript\n// netlify/functions/identity.mts — deny a signup\nimport type { UserValidateEvent } from \"@netlify/functions\"\n\nexport default {\n  userValidate(event: UserValidateEvent) {\n    if (!event.user.email?.endsWith(\"@example.com\")) return event.deny()\n  },\n}\n```\n\n```typescript\n// netlify/functions/identity.mts — assign roles at signup\nimport type { UserSignupEvent } from \"@netlify/functions\"\n\nexport default {\n  userSignup(event: UserSignupEvent) {\n    return { user: { ...event.user, appMetadata: { ...event.user.appMetadata, roles: [\"member\"] } } }\n  },\n}\n```\n\n- `event.deny()` rejects the action. The end user gets a `401`, and no error appears in observability. The first handler to call it aborts the chain, and later subscribers are not invoked. Legacy filename functions signal denial with a non-2xx `Response` instead.\n- Return `{ user: {...} }` to modify the record before it is persisted. This is the canonical way to set roles at signup. Roles ride in the JWT, so a role change takes effect on the user's **next login or token refresh, not immediately**. See Roles & the JWT below.\n- Background mode: `export const config: Config = { background: true }`. The action completes immediately and the handler runs asynchronously.\n\n## Roles & the JWT\n\n- `user.roles` is read from `app_metadata.roles` and carried in the JWT (cookie `nf_jwt`; refresh via `nf_refresh`).\n- `user_metadata` holds the user-editable profile (`full_name`, `email`). `app_metadata` holds app data, including `roles`, and is not user-editable.\n\n> **Role changes are NOT immediate.** They take effect on next login or token refresh. Changing roles does not invalidate the current JWT. Force a refresh with `refreshSession()`.\n\nSet roles for existing users via `admin.updateUser()` in a Netlify Function. Set them at signup via the `userSignup` event handler above.\n\nDeep guides for SSR/session hydration and authorization live in `references/advanced-patterns.md` and `references/authorization-and-sessions.md`.\n\n## CDN-edge RBAC (redirect rules)\n\nEnforced at the edge with no origin round trip. A mismatched role gets a 404 unless you add a fallback. **Always pair a role-gated rule with a fallback.**\n\n`_redirects`:\n```\n/admin/*  /admin/:splat  200!  Role=admin\n/admin/*  /login         401!\n# Multiple roles chained with commas:\n/private/* /private/:splat 200! Role=editor,admin\n```\n\n`netlify.toml`:\n```toml\n[[redirects]]\n  from = \"/admin/*\"\n  to = \"/admin/:splat\"\n  force = true\n  status = 200\n  conditions = {Role = [\"editor\", \"admin\"]}\n```\n\nUse redirect rules for path-based gating. Use function-based `user.roles` checks for custom authorization logic.\n\n## Configuration (dashboard-only)\n\nBase: `https://app.netlify.com/projects/{site_name}/identity`. Enable with **Enable Identity**. Identity requires HTTPS, so set up SSL before integrating on a custom domain.\n\n- **Registration** (`?tab=registration#registration-preferences`): **Open** (default; anyone can sign up) or **Invite only** (all users, including external-provider logins, must be invited first).\n- **Confirmation / autoconfirm** (`?tab=emails#confirmation-template`): check the box to skip email verification.\n- **External providers** (`?tab=registration#external-providers`): Google/GitHub/GitLab/Bitbucket. For branded OAuth (your app name instead of \"Netlify Identity\"), register your app with the provider, get a client ID and secret, and enter them **in the Netlify settings UI**, not in code.\n- **Invitations** (`?tab=users`): enter addresses to send invites. The link carries `invite_token`. Complete it with `handleAuthCallback()` + `acceptInvite(token, password)` as shown above.\n- **Password recovery**: on the user page, use **Send reset password email**. The link carries `recovery_token`.\n\n### Emails (Pro plans or higher)\n\nThe default sender is `no-reply@netlify.com`. A custom SMTP sender and custom templates both require **Pro plans or higher**.\n\nTemplate variables (Go syntax): `{{ .Email }}`, `{{ .NewEmail }}` (email-change only), `{{ .SiteURL }}`, `{{ .ConfirmationURL }}`, `{{ .Token }}`.\n\nCustom-link hash fragments per action:\n```\n{{ .SiteURL }}/path/#invite_token={{ .Token }}\n{{ .SiteURL }}/path/#confirmation_token={{ .Token }}\n{{ .SiteURL }}/path/#recovery_token={{ .Token }}\n{{ .SiteURL }}/path/#email_change_token={{ .Token }}\n```\n\nCustom template constraints:\n- Inline CSS only.\n- Absolute image links.\n- **No `<html>`/`<head>`/`<body>` tags.**\n- Ensure your build doesn't alter Go template variables.\n\n### Audit log (Pro plans or higher)\n\n`?tab=audit-log`. Search with a scoped term: `author:[string]` or `action:[string]`.\n\nAction names: `login`, `logout`, `user_signedup`, `user_deleted`, `user_modified`, `token_revoked`, `token_refreshed`, `user_recovery_requested`, `user_invited`.\n\n## External JWT providers (Enterprise)\n\nAvailable on **Enterprise plans**. You may use Netlify Identity OR an external JWT provider, **not both at once**. You cannot authenticate third-party JWTs while Netlify Identity is enabled.\n\n- Roles path: Netlify Identity uses `app_metadata.roles`; an external provider uses `app_metadata.authorization.roles`. For a custom path, contact support.\n- The JWT header must be `{\"alg\": \"HS256\", \"typ\": \"JWT\"}` (HS256 required). The payload `exp` is required and must be a future Unix Epoch time.\n- Set the JWT secret at `Project configuration > General > Visitor access > JWT secret`. Project-level settings override team-level defaults.\n\n## On failure — stop, don't guess\n\nIf callbacks 404, `/.netlify/identity/*` is unreachable, or an OAuth flow never returns:\n1. Surface the error.\n2. Give the dashboard URL (`https://app.netlify.com/projects/{site_name}/identity`).\n3. Name the setting to check (registration preference, external provider config, confirmation/autoconfirm).\n4. Then stop. Do not invent recovery commands.\n\nRemember: Identity does not work under `netlify dev`. Confirm you are testing on a deploy.\n\nSite-gating requests (\"lock this site to my company\", employees-only) route to the netlify-access-control skill first. Identity is the app-level user layer only. Restricting who can view the whole project uses [project visibility](https://docs.netlify.com/manage/security/secure-access-to-sites/project-visibility) or [Password Protection](https://docs.netlify.com/manage/security/secure-access-to-sites/password-protection), not Identity.\n\n<!-- gap: getSettings() signature/return shape is not documented in the intermediate. -->\n<!-- gap: handleAuthCallback() result.type strings other than 'invite' are not enumerated. -->\n\n<!-- system: agent-context/identity/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (identity)\n\nThese are org conventions, not docs facts — merged into the rendered skill by\nctx-gen and never generated. Owned by the skills maintainer.\n\n1. Deep guides live in this skill: `references/advanced-patterns.md`\n   (SSR/session hydration) and `references/authorization-and-sessions.md`.\n2. Identity does not work under `netlify dev` — test auth flows on deploys\n   (Deploy Previews work).\n3. Identity configuration has no public API — it is dashboard-only. Never curl\n   `api.netlify.com` to flip or inspect Identity settings, never read auth\n   tokens from `~/Library/Preferences/netlify/config.json`, never probe for\n   undocumented endpoints.\n4. On failure (callback 404s, `/.netlify/identity/*` unreachable, OAuth flow\n   doesn't return), surface the error, the dashboard URL, and the setting to\n   check — then stop. Do not invent recovery commands.\n5. Never build a from-scratch third-party OAuth flow when Identity is in play —\n   no provider app registration, no `client_id`/`secret` in code, no custom\n   callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`;\n   raw OAuth beside Identity is the single most common source of rework.\n6. Server-side `getUser()`/`login()`/`admin.*` require modern v2 functions\n   (`export default`) — v1 `export { handler }` is not supported. Typed\n   Identity event handlers (`UserSignupEvent`, `event.deny()`) require\n   `@netlify/functions` ≥ 5.2.0; older installs use the legacy filenames.\n7. Don't hard-code which auth providers exist — call `getSettings()` at\n   startup and render the signup form and OAuth buttons from what it returns.\n8. Site-gating requests (\"lock this site to my company\", employees-only)\n   route to the netlify-access-control skill first — Identity is the\n   app-level user layer only.\n9. Any answer that assigns or changes roles — at signup, via `admin.*`, or in\n   the dashboard — must say the change takes effect on the user's next login\n   or token refresh, not immediately. Keep that sentence next to the code that\n   sets the role, not only in a separate JWT section: an agent answering a\n   signup question reads the signup example and stops, and it has shipped\n   answers that omit the delay.\n10. Before setting up Identity for an internal tool, ask who signs in. If\n    they can already pass the project's Netlify login (a private project or\n    team login protection), the app has a verified user without Identity:\n    read `context.user` in functions and edge functions and skip the second\n    login. Identity is for users outside that Netlify login. The two never\n    merge: `context.user` has no roles or `app_metadata`, and `getUser()`\n    never returns it.\n"
Full snapshot data
{
  "description": "Add user authentication to a Netlify site with @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, accepting user invites, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.",
  "included_files": [
    {
      "relative_path": "references/advanced-patterns.md",
      "size_in_bytes": 4428
    },
    {
      "relative_path": "references/authorization-and-sessions.md",
      "size_in_bytes": 3384
    }
  ],
  "name": "netlify-identity",
  "skill_md_contents": "---\nname: netlify-identity\ndescription: Add user authentication to a Netlify site with @netlify/identity, covering signup/login/logout, Google/GitHub/GitLab/Bitbucket OAuth, server-side getUser() checks, role-based access control, and Identity event functions. Use it when a task involves adding a login or signup form, gating content to members or roles, \"auth middleware\" or verifying users in Netlify Functions or Edge Functions, handling OAuth or email-confirmation callbacks, accepting user invites, assigning roles at signup, or customizing Identity emails. For locking a whole site to your company or employees-only access, use netlify-access-control instead.\n---\n\n# Netlify Identity\n\nUse `@netlify/identity` (npm). For new projects it replaces the legacy `netlify-identity-widget` and `gotrue-js`. Do not reach for those.\n\n```bash\nnpm install @netlify/identity\n```\n\nFramework examples (Next.js/Astro/Remix/SvelteKit) and the full API reference are in the [`@netlify/identity` README on npm](https://www.npmjs.com/package/@netlify/identity).\n\n> **Identity does not run under `netlify dev`.** Test all auth flows on a deploy. Deploy Previews work. Local dev will not complete signup/login/OAuth.\n\n> **Identity config is dashboard-only. There is no public API.** Never curl `api.netlify.com` to flip or read Identity settings, never read tokens from local Netlify config, and never probe undocumented endpoints. Enable and configure Identity at `https://app.netlify.com/projects/{site_name}/identity`.\n\n> **Never build a from-scratch OAuth flow alongside Identity.** No provider app registration in code, no `client_id`/`secret` in source, and no custom callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`. Raw OAuth beside Identity is the most common source of rework.\n\n## Client auth (browser)\n\n```ts\nimport { signup, login, logout, getUser, oauthLogin, handleAuthCallback } from '@netlify/identity'\n\n// Register — confirmation email sent by default (unless autoconfirm is on)\nconst user = await signup('jane@example.com', 'securepassword', { full_name: 'Jane Doe' })\n\n// Log in / out\nawait login('jane@example.com', 'securepassword')\nawait logout()\n\n// Current user or null\nconst current = await getUser()\nif (current) console.log(`Logged in as ${current.email}`)\n\n// External provider — redirects the browser; provider is one of\n// 'google' | 'github' | 'gitlab' | 'bitbucket'\noauthLogin('github')\n```\n\n> **`handleAuthCallback()` is mandatory on your landing page.** Without it, OAuth redirects, email-confirmation links, password-recovery links, and invite links never complete. Call it on page load.\n\n> **Invites are NOT logged in by `handleAuthCallback()`.** For an invite it returns `type === 'invite'` with the token in `result.token` and `result.user === null`. The account does not exist yet. You must collect a password and call `acceptInvite(result.token, password)`. If you skip this step, invited users never get an account.\n\n```ts\nimport { handleAuthCallback, acceptInvite } from '@netlify/identity'\n\nconst result = await handleAuthCallback() // falsy if no token in URL hash\nif (result?.type === 'invite' && result.token) {\n  // Invited user has no account yet. Ask them to choose a password first.\n  const password = (document.getElementById('password') as HTMLInputElement).value\n  const user = await acceptInvite(result.token, password)\n  console.log('Account created:', user.email)\n} else if (result) {\n  // OAuth, email confirmation, recovery, or email change\n  console.log(result.type, result.user?.email)\n}\n```\n\nFor recovery tokens you can call `recoverPassword()` directly instead. Refresh a session with `refreshSession()`.\n\nDon't hard-code which providers exist. Call `getSettings()` at startup and render the signup form and OAuth buttons from what it returns.\n\n## Server-side auth (Netlify Functions & Edge Functions)\n\nServer-side `getUser()`/`login()`/`admin.*` require modern **v2 functions** (`export default`). The v1 `export { handler }` form is not supported.\n\n`getUser()` works in both runtimes. **`admin.*` runs ONLY in Netlify Functions. It does not run in the browser or in Edge Functions.**\n\n```ts\n// netlify/functions/me.ts — verify user\nimport { getUser } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  return Response.json({ id: user.id, email: user.email })\n}\n```\n\nThe Edge Function form is identical but imports `Context` from `@netlify/edge-functions`.\n\n### Role checks\n\n```ts\n// netlify/functions/admin-users.ts\nimport { getUser, admin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  const user = await getUser()\n  if (!user) return new Response('Unauthorized', { status: 401 })\n  if (!user.roles.includes('admin')) return new Response('Forbidden', { status: 403 })\n  const users = await admin.listUsers()\n  return Response.json({ users })\n}\n```\n\n### CSRF: required for server-side auth endpoints\n\n> Any endpoint that runs `login()`, `signup()`, or `logout()` server-side **must** call `verifyRequestOrigin(req)` at the top of the handler. It throws a 403 on origin mismatch.\n\n```ts\n// netlify/functions/login.ts\nimport { login, verifyRequestOrigin } from '@netlify/identity'\nimport type { Context } from '@netlify/functions'\n\nexport default async (req: Request, context: Context) => {\n  verifyRequestOrigin(req)\n  const { email, password } = await req.json()\n  await login(email, password)\n  return new Response(null, { status: 302, headers: { Location: '/dashboard' } })\n}\n```\n\n## Identity event functions\n\nThe platform calls your handler when an Identity event occurs. Export a default object with a method per event. File: `netlify/functions/identity.mts`.\n\n> Typed handlers (`UserSignupEvent`, `event.deny()`) require `@netlify/functions` ≥ 5.2.0. Older installs must use the legacy filename convention (`identity-signup.ts`, etc.). See `references/authorization-and-sessions.md`.\n\n| Handler | Fires when |\n|---|---|\n| `userValidate` | Signup attempt, before account creation. Block bad signups here. |\n| `userSignup` | Signup completes (after email confirmation if enabled). Assign roles, sync, welcome. |\n| `userLogin` | User logs in. Track/last-seen/block. |\n| `userModified` | Profile updated. |\n| `userDeleted` | User deleted (notification only). |\n\nEvent `user` fields are camelCase (`appMetadata`, `userMetadata`, `confirmedAt`).\n\n```typescript\n// netlify/functions/identity.mts — deny a signup\nimport type { UserValidateEvent } from \"@netlify/functions\"\n\nexport default {\n  userValidate(event: UserValidateEvent) {\n    if (!event.user.email?.endsWith(\"@example.com\")) return event.deny()\n  },\n}\n```\n\n```typescript\n// netlify/functions/identity.mts — assign roles at signup\nimport type { UserSignupEvent } from \"@netlify/functions\"\n\nexport default {\n  userSignup(event: UserSignupEvent) {\n    return { user: { ...event.user, appMetadata: { ...event.user.appMetadata, roles: [\"member\"] } } }\n  },\n}\n```\n\n- `event.deny()` rejects the action. The end user gets a `401`, and no error appears in observability. The first handler to call it aborts the chain, and later subscribers are not invoked. Legacy filename functions signal denial with a non-2xx `Response` instead.\n- Return `{ user: {...} }` to modify the record before it is persisted. This is the canonical way to set roles at signup. Roles ride in the JWT, so a role change takes effect on the user's **next login or token refresh, not immediately**. See Roles & the JWT below.\n- Background mode: `export const config: Config = { background: true }`. The action completes immediately and the handler runs asynchronously.\n\n## Roles & the JWT\n\n- `user.roles` is read from `app_metadata.roles` and carried in the JWT (cookie `nf_jwt`; refresh via `nf_refresh`).\n- `user_metadata` holds the user-editable profile (`full_name`, `email`). `app_metadata` holds app data, including `roles`, and is not user-editable.\n\n> **Role changes are NOT immediate.** They take effect on next login or token refresh. Changing roles does not invalidate the current JWT. Force a refresh with `refreshSession()`.\n\nSet roles for existing users via `admin.updateUser()` in a Netlify Function. Set them at signup via the `userSignup` event handler above.\n\nDeep guides for SSR/session hydration and authorization live in `references/advanced-patterns.md` and `references/authorization-and-sessions.md`.\n\n## CDN-edge RBAC (redirect rules)\n\nEnforced at the edge with no origin round trip. A mismatched role gets a 404 unless you add a fallback. **Always pair a role-gated rule with a fallback.**\n\n`_redirects`:\n```\n/admin/*  /admin/:splat  200!  Role=admin\n/admin/*  /login         401!\n# Multiple roles chained with commas:\n/private/* /private/:splat 200! Role=editor,admin\n```\n\n`netlify.toml`:\n```toml\n[[redirects]]\n  from = \"/admin/*\"\n  to = \"/admin/:splat\"\n  force = true\n  status = 200\n  conditions = {Role = [\"editor\", \"admin\"]}\n```\n\nUse redirect rules for path-based gating. Use function-based `user.roles` checks for custom authorization logic.\n\n## Configuration (dashboard-only)\n\nBase: `https://app.netlify.com/projects/{site_name}/identity`. Enable with **Enable Identity**. Identity requires HTTPS, so set up SSL before integrating on a custom domain.\n\n- **Registration** (`?tab=registration#registration-preferences`): **Open** (default; anyone can sign up) or **Invite only** (all users, including external-provider logins, must be invited first).\n- **Confirmation / autoconfirm** (`?tab=emails#confirmation-template`): check the box to skip email verification.\n- **External providers** (`?tab=registration#external-providers`): Google/GitHub/GitLab/Bitbucket. For branded OAuth (your app name instead of \"Netlify Identity\"), register your app with the provider, get a client ID and secret, and enter them **in the Netlify settings UI**, not in code.\n- **Invitations** (`?tab=users`): enter addresses to send invites. The link carries `invite_token`. Complete it with `handleAuthCallback()` + `acceptInvite(token, password)` as shown above.\n- **Password recovery**: on the user page, use **Send reset password email**. The link carries `recovery_token`.\n\n### Emails (Pro plans or higher)\n\nThe default sender is `no-reply@netlify.com`. A custom SMTP sender and custom templates both require **Pro plans or higher**.\n\nTemplate variables (Go syntax): `{{ .Email }}`, `{{ .NewEmail }}` (email-change only), `{{ .SiteURL }}`, `{{ .ConfirmationURL }}`, `{{ .Token }}`.\n\nCustom-link hash fragments per action:\n```\n{{ .SiteURL }}/path/#invite_token={{ .Token }}\n{{ .SiteURL }}/path/#confirmation_token={{ .Token }}\n{{ .SiteURL }}/path/#recovery_token={{ .Token }}\n{{ .SiteURL }}/path/#email_change_token={{ .Token }}\n```\n\nCustom template constraints:\n- Inline CSS only.\n- Absolute image links.\n- **No `<html>`/`<head>`/`<body>` tags.**\n- Ensure your build doesn't alter Go template variables.\n\n### Audit log (Pro plans or higher)\n\n`?tab=audit-log`. Search with a scoped term: `author:[string]` or `action:[string]`.\n\nAction names: `login`, `logout`, `user_signedup`, `user_deleted`, `user_modified`, `token_revoked`, `token_refreshed`, `user_recovery_requested`, `user_invited`.\n\n## External JWT providers (Enterprise)\n\nAvailable on **Enterprise plans**. You may use Netlify Identity OR an external JWT provider, **not both at once**. You cannot authenticate third-party JWTs while Netlify Identity is enabled.\n\n- Roles path: Netlify Identity uses `app_metadata.roles`; an external provider uses `app_metadata.authorization.roles`. For a custom path, contact support.\n- The JWT header must be `{\"alg\": \"HS256\", \"typ\": \"JWT\"}` (HS256 required). The payload `exp` is required and must be a future Unix Epoch time.\n- Set the JWT secret at `Project configuration > General > Visitor access > JWT secret`. Project-level settings override team-level defaults.\n\n## On failure — stop, don't guess\n\nIf callbacks 404, `/.netlify/identity/*` is unreachable, or an OAuth flow never returns:\n1. Surface the error.\n2. Give the dashboard URL (`https://app.netlify.com/projects/{site_name}/identity`).\n3. Name the setting to check (registration preference, external provider config, confirmation/autoconfirm).\n4. Then stop. Do not invent recovery commands.\n\nRemember: Identity does not work under `netlify dev`. Confirm you are testing on a deploy.\n\nSite-gating requests (\"lock this site to my company\", employees-only) route to the netlify-access-control skill first. Identity is the app-level user layer only. Restricting who can view the whole project uses [project visibility](https://docs.netlify.com/manage/security/secure-access-to-sites/project-visibility) or [Password Protection](https://docs.netlify.com/manage/security/secure-access-to-sites/password-protection), not Identity.\n\n<!-- gap: getSettings() signature/return shape is not documented in the intermediate. -->\n<!-- gap: handleAuthCallback() result.type strings other than 'invite' are not enumerated. -->\n\n<!-- system: agent-context/identity/system.md — human-owned, merged by ctx-gen; edit system.md, not this section -->\n# Netlify house rules (identity)\n\nThese are org conventions, not docs facts — merged into the rendered skill by\nctx-gen and never generated. Owned by the skills maintainer.\n\n1. Deep guides live in this skill: `references/advanced-patterns.md`\n   (SSR/session hydration) and `references/authorization-and-sessions.md`.\n2. Identity does not work under `netlify dev` — test auth flows on deploys\n   (Deploy Previews work).\n3. Identity configuration has no public API — it is dashboard-only. Never curl\n   `api.netlify.com` to flip or inspect Identity settings, never read auth\n   tokens from `~/Library/Preferences/netlify/config.json`, never probe for\n   undocumented endpoints.\n4. On failure (callback 404s, `/.netlify/identity/*` unreachable, OAuth flow\n   doesn't return), surface the error, the dashboard URL, and the setting to\n   check — then stop. Do not invent recovery commands.\n5. Never build a from-scratch third-party OAuth flow when Identity is in play —\n   no provider app registration, no `client_id`/`secret` in code, no custom\n   callback token exchange. Use `oauthLogin()` + `handleAuthCallback()`;\n   raw OAuth beside Identity is the single most common source of rework.\n6. Server-side `getUser()`/`login()`/`admin.*` require modern v2 functions\n   (`export default`) — v1 `export { handler }` is not supported. Typed\n   Identity event handlers (`UserSignupEvent`, `event.deny()`) require\n   `@netlify/functions` ≥ 5.2.0; older installs use the legacy filenames.\n7. Don't hard-code which auth providers exist — call `getSettings()` at\n   startup and render the signup form and OAuth buttons from what it returns.\n8. Site-gating requests (\"lock this site to my company\", employees-only)\n   route to the netlify-access-control skill first — Identity is the\n   app-level user layer only.\n9. Any answer that assigns or changes roles — at signup, via `admin.*`, or in\n   the dashboard — must say the change takes effect on the user's next login\n   or token refresh, not immediately. Keep that sentence next to the code that\n   sets the role, not only in a separate JWT section: an agent answering a\n   signup question reads the signup example and stops, and it has shipped\n   answers that omit the delay.\n10. Before setting up Identity for an internal tool, ask who signs in. If\n    they can already pass the project's Netlify login (a private project or\n    team login protection), the app has a verified user without Identity:\n    read `context.user` in functions and edge functions and skip the second\n    login. Identity is for users outside that Netlify login. The two never\n    merge: `context.user` has no roles or `app_metadata`, and `getUser()`\n    never returns it.\n"
}

SHA-256 of public snapshot: ff2a4a0ab3f20059fb50344848bfad375539bbfb5d2a3c22dc98c538f0cca73b