references/managed-auth.md
# Managed Better Auth: implement login
Enabling `auth: true` is not implementing login. Follow the matching live quickstart, then verify sign-up, sign-in, sign-out, session, and a protected route.
- Overview: https://neon.com/docs/auth/overview.md
- Next.js (API methods): https://neon.com/docs/auth/quick-start/nextjs-api-only.md
- React (API methods, including React Router): https://neon.com/docs/auth/quick-start/react.md
- TanStack Router (UI components): https://neon.com/docs/auth/quick-start/tanstack-router.md
Keep Clerk, existing Better Auth, Supabase Auth, or another working provider. Do not migrate it unless the user asks. The `SKILL.md` Supabase case is that explicit login-migration request.
Framework-specific companion skills also live in [neondatabase/neon-js](https://github.com/neondatabase/neon-js) (`neon-auth-nextjs`, `neon-auth-react`, `neon-js-react`). Prefer the live Neon guides above; do not copy those SDK-local files into this repo.
## Auth emails
Managed Auth sends verification, email OTP, magic-link, and password-reset messages. Getting started uses the shared SMTP provider (`auth@mail.myneon.app`). Implementing login does not require Resend, SendGrid, or other application email code.
Production requires custom SMTP. Verification codes work on shared or custom SMTP. Verification links require custom SMTP. Checklist: https://neon.com/docs/auth/production-checklist.md. Branding and webhook delivery: https://neon.com/docs/auth/guides/customize-emails.md.
SMS is separate: the Phone Number plugin needs an application `send.otp` webhook.
## Packages
| Need | Package |
| --- | --- |
| Auth only | `@neon/auth` |
| Already using the combined SDK | `@neon/neon-js/auth` re-export |
| Pre-built UI | Better Auth UI: `@better-auth-ui/react` plus shadcn/ui components (`npx shadcn add @better-auth-ui/auth`) |
Keep an existing `SupabaseAuthAdapter()` caller on that API (`signInWithPassword`, `signInWithOAuth`). Do not mix those methods into default Better Auth examples. Password hashes do not migrate from Supabase; `updateUser()` cannot change email or password; email verification needs app UI. Guide: https://neon.com/docs/auth/migrate/from-supabase.md
The Managed client is Better Auth methods through Neon's wrapper. It is not interchangeable with bare `better-auth/client` while Auth is managed: the wrapper rejects extra plugins and implements Neon OAuth verifier / iframe popup / JWT extraction.
## Environment
| Variable | Purpose |
| --- | --- |
| `NEON_AUTH_BASE_URL` | Branch Managed Auth URL (includes path). Next server; injected into Functions. |
| `NEON_AUTH_COOKIE_SECRET` | Next app secret for cached session cookies. Generate with `openssl rand -base64 32` (32+ characters). Not injected by Neon. |
| `VITE_NEON_AUTH_URL` | Public Auth URL for Vite / TanStack browser code. Assign the actual branch URL; env pull does not create this alias. |
| `NEON_AUTH_JWKS_URL` | Injected Functions JWKS. Verify tokens in `neon-functions`, not here. |
`neon env pull` / `neon deploy` write Managed `NEON_AUTH_BASE_URL` and `NEON_AUTH_JWKS_URL` when Auth is declared. The cookie secret and `VITE_*` name are application config.
## Next.js
`createNeonAuth` from `@neon/auth/next/server`. Optional Next peer on current `@neon/auth` is `>=16.0.0`; check the installed package before changing an existing app's router file.
```typescript
import { createNeonAuth } from "@neon/auth/next/server";
export const auth = createNeonAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!,
cookies: { secret: process.env.NEON_AUTH_COOKIE_SECRET! },
});
```
`app/api/auth/[...path]/route.ts`:
```typescript
import { auth } from "@/lib/auth/server";
export const { GET, POST, PUT, DELETE, PATCH } = auth.handler();
```
Those five methods are what the installed SDK returns. Existing apps that export only `GET`/`POST` keep serving GET/POST routes.
Browser client takes **no arguments** and talks to that same-origin proxy:
```typescript
import { createAuthClient } from "@neon/auth/next";
export const authClient = createAuthClient();
```
### Middleware
Protect routes with `auth.middleware()` from `proxy.ts` on Next 16. Earlier Next apps may still use `middleware.ts`; match the installed SDK. Use the catch-all matcher and list only the app's own public pages in `publicRoutes`:
```typescript
import { auth } from "@/lib/auth/server";
export default auth.middleware({
loginUrl: "/auth/sign-in",
publicRoutes: ["/"],
});
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```
- `/api/auth` and every Better Auth UI signed-out view (sign-in, sign-up, forgot-password, reset-password, verify-email, magic-link, accept-invitation, and the rest) are public by default. `/auth` itself and `/settings/*` stay protected.
- `publicRoutes` matches an exact path or its slash-delimited subpaths. `"/"` matches only `/`. Entries must start with `/`; `""` and `"//"` throw.
- Do not write a custom `proxy.ts` wrapper or re-list the default skip routes.
Before reading protected data or performing a mutation, check the session inside the Route Handler or Server Action and enforce the resource's authorization rules. Verify direct unauthenticated requests are denied, independently of page redirects:
```typescript
const { data: session } = await auth.getSession();
if (!session?.user) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
```
Server session:
```typescript
const { data: session, error } = await auth.getSession();
const user = session?.user;
```
Do not destructure `{ user }` from the top-level result. Do not pass options into `createAuthClient()` from `/next`. Do not put `fetchOptions` on the Managed `createAuthClient` URL-style config; adapter factories accept fetch options inside `BetterAuthReactAdapter({ fetchOptions })` / `BetterAuthVanillaAdapter(...)`.
JWT: `const { data, error } = await auth.token();` then `data.token`. Do not call `getJWTToken()` on the public client.
**Phone OTP:** the browser client exposes `phoneNumber`. Existing users link a number, then sign in; there is no phone-first signup. Next.js `auth.handler()` forwards the catch-all path to Managed Auth, including phone OTP. A missing `auth.phoneNumber` server method is a missing typed helper, not a proxy rejection. SMS e2e needs a configured `send.otp` webhook and custom UI.
## Organization invitations
`organization.inviteMember()` does not send email unless `send_invitation_email` is on (default `false`) and "Verify email at signup" is enabled. Accepting an emailed invite needs `/auth/accept-invitation?invitationId=` via Better Auth UI's organization plugin (`organizationPlugin()`, view `accept-invitation`) or a custom flow that signs the recipient in and calls `organization.acceptInvitation({ invitationId })`. If email delivery stays off, use an in-app invitation list. https://neon.com/docs/auth/guides/plugins/organization.md
## React / Vite
```typescript
import { createAuthClient } from "@neon/auth";
import { BetterAuthReactAdapter } from "@neon/auth/react/adapters";
export const authClient = createAuthClient(import.meta.env.VITE_NEON_AUTH_URL, {
adapter: BetterAuthReactAdapter(),
});
```
Vite has no server middleware. Guard protected routes with a session check, for example a router loader that calls `authClient.getSession()` or `useSession()` in a layout component, and redirect to `/auth/sign-in` when there is no user. Add `http://localhost:5173` and the production origin as trusted domains first: see [Trusted domains](../SKILL.md#trusted-domains).
Call adapter factories with `()`. Omit the adapter for vanilla Better Auth methods without `useSession`.
Public calls: `signUp.email({ email, password, name })`, `signIn.email({ email, password })`, `signIn.social({ provider, callbackURL })`, `getSession()`, `signOut()`. Result shape is `{ data, error }`; user is `data.user`. Handle `error` and thrown HTTP errors, pending UI, and authenticated vs unauthenticated display.
JWT: `authClient.token()` then `data.token`.
## UI
Neon hosts the auth server. Do NOT call `betterAuth()`, add a database adapter, or run Better Auth migrations.
Better Auth UI 1.7. The shadcn CLI copies its components into the app; `@better-auth-ui/react` is the data layer and needs TanStack Query:
```bash
npx shadcn@latest init # once, if the app has no components.json
npx shadcn@latest add @better-auth-ui/auth # sign-in, sign-up, password reset
npx shadcn@latest add @better-auth-ui/user-button # optional
```
```tsx
import { getSafeRedirectTo, viewPaths } from "@better-auth-ui/core";
import { QueryClientProvider } from "@tanstack/react-query";
import { AuthProvider } from "@/components/auth/auth-provider";
import { Auth } from "@/components/auth/auth";
import { Toaster } from "@/components/ui/sonner";
<QueryClientProvider client={queryClient}>
<AuthProvider
authClient={authClient}
emailAndPassword={{ requireEmailVerification: false }} // match the branch's "Verify email at signup"
navigate={({ to, replace }) => {
const path = getSafeRedirectTo(to, window.location.origin);
const target = path.startsWith("//") ? "/" : path;
if (replace) router.replace(target);
else router.push(target);
}}
Link={Link}
redirectTo="/"
>
{children}
<Toaster />
</AuthProvider>
</QueryClientProvider>
// /auth/[path]: valid paths are Object.values(viewPaths.auth)
<Auth path={path} />
```
- `queryClient`, `router` and `Link` are the app's own TanStack Query client and its framework router's `push`/`replace` and `Link`; do not invent imports for them.
- Pass the Neon `authClient` as is; it satisfies Better Auth UI's `AuthClient` type.
- `navigate` receives the URL's `?redirectTo=` after sign-in. Validate it as above: `getSafeRedirectTo` alone returns `//host` for `/a/..//host`.
- Install with one command and let npm resolve it: `npm i @neon/auth @better-auth-ui/core @better-auth-ui/react @tanstack/react-query`. `@neon/auth` declares the Better Auth range, so npm installs a single compatible copy. Do not pin `better-auth` or its plugins, and do not add `overrides` or `resolutions`.
- After the last `npx shadcn add`, run `npm i better-auth@~1.7.12`. The registry items install a bare `better-auth`, which resolves to a newer prerelease and leaves two copies; this range matches `@neon/auth`.
- Protect pages on the server (`auth.middleware()`, see [Middleware](#middleware)). Better Auth UI's `useAuthenticate` redirects while a stale signed-out session is still refetching, which sends a user who just signed up back to sign-in.
- Render `<Toaster />`: the copied `AuthProvider` reports errors with Sonner's `toast.error()` and renders nothing itself.
- Set `requireEmailVerification` to the branch's "Verify email at signup" setting (off by default). It decides whether sign-up shows the verify-email view.
- Better Auth UI plugins (`plugins={[...]}`) do not enable the Managed plugin. Configure the plugin on the branch, then the UI.
Verify before reporting done:
1. Sign up a new user.
2. Sign out, then sign in again.
3. The session survives a reload.
4. A protected route redirects to `/auth/sign-in` while signed out.
5. A wrong password shows an invalid-credentials message, not a generic one.
6. `/auth/reset-password` loads while signed out.
Leave an existing app on `@neondatabase/auth-ui` alone rather than migrating it as a drive-by. New snippets use Better Auth UI.
## Cross-subdomain vs bearer JWT
`cookies.domain` shares session cookies across subdomains of one parent domain (see the neon-js `cross-domain-cookies` example). That is not cookie sharing across unrelated frontend and backend hosts. A Neon Function authenticates with `Authorization: Bearer`. With Managed Auth, verify against the injected JWKS. With another identity, use that identity's token contract — see `neon-functions`. https://neon.com/docs/compute/functions/authentication.md and https://neon.com/docs/auth/guides/plugins/jwt.md.
## Data API identity
Only when the app already uses PostgREST or a Supabase database client:
```typescript
import { defineConfig } from "@neon/config/v1";
export default defineConfig({ auth: true, dataApi: true });
```
Existing external IdP:
```typescript
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
dataApi: {
authProvider: "external",
jwksUrl: "https://your-idp/.well-known/jwks.json",
},
});
```
Do not enable Auth merely to satisfy a `dataApi` type error in an app that never needed the Data API. External JWKS on a Claimable project is accepted only after claim. Combined SDK `createClient({ dataApi: { url, getToken } })` is a query client without `.auth`; confirm the installed `@neon/neon-js` docs before introducing it.
references/oauth-server.md
# Managed Better Auth as the OAuth server
Use this page when the request is "let MCP clients sign in my users", "protect my MCP server with OAuth", or "let another app or OAuth client call my API on behalf of my users". Managed Better Auth is the OAuth 2.1 / OIDC authorization server (the OAuth provider plugin, beta, available to all Managed projects). Do not move to self-managed Better Auth for this, and keep the app's existing login method.
"OAuth server" and "OAuth clients" here are not the social providers (Google, GitHub, Apple) of `neon neon-auth oauth-provider`. Those sign users in to Neon Auth. This page makes Neon Auth issue tokens to other apps.
- Docs: https://neon.com/docs/auth/guides/plugins/oauth-provider.md
- Configuration is per branch: each branch has its own issuer, clients, and settings.
- Prerequisites: Auth enabled; a login page and a consent page that you host (there is no default UI); the origin of each page on the branch's [trusted domains](../SKILL.md#trusted-domains); at least one protected resource (the MCP server URL, or an API identifier URL).
## 1. Enable and configure the server
CLI (Console and the API `PATCH .../branches/{branch_id}/auth/plugins/oauth-provider` do the same):
```bash
# MCP server
neon neon-auth config oauth-server update --enabled \
--login-page https://app.example.com/auth/sign-in \
--consent-page https://app.example.com/auth/consent \
--mcp-resource https://mcp.example.com/mcp
# A non-MCP API instead (or as well)
neon neon-auth config oauth-server resource add https://api.example.com/reports
neon neon-auth config oauth-server get
```
- Enabling needs both pages and at least one of `--mcp-resource` or a resource. Resources are absolute `https` URLs (or `http` on loopback) with no query or fragment, and they must not be the Auth host. They do not need to resolve.
- `--mcp-resource` turns on Client ID Metadata Documents (CIMD): MCP clients that support CIMD identify themselves, so you create no client for them. Turn it off with `--no-mcp-client-id-metadata-documents` to allow only clients you create. Legacy dynamic registration is off by default; leave it off.
- Keep the MCP server URL in `--mcp-resource`, not in the resources list.
- `resource add|remove` rewrites the full stored list. `--resources` replaces it.
Programmatic equivalents: `neon.auth.oauthServer.get|update` and `neon.auth.oauthClients.*` in `@neon/sdk`, and the `get_auth_oauth_server` / `update_auth_oauth_server` / `*_auth_oauth_client` tools in the Neon MCP server (`neon_auth` scope).
## 2. Register clients
Skip this for MCP clients that use CIMD. Create managed clients for known apps, for non-MCP resources, or when CIMD is off. Every `--resources` URL must already be configured on the server.
```bash
neon neon-auth oauth-client create --name "Reports" --type confidential \
--redirect-uris https://reports.example.com/callback \
--resources https://api.example.com/reports
neon neon-auth oauth-client list
neon neon-auth oauth-client get <client-id>
neon neon-auth oauth-client update <client-id> --redirect-uris https://reports.example.com/callback
neon neon-auth oauth-client rotate-secret <client-id>
neon neon-auth oauth-client delete <client-id>
```
- `confidential` (server-side apps, token endpoint auth `client_secret_basic`) or `public` (SPA, mobile, desktop, CLI; PKCE, no secret). The type cannot change after creation.
- The `client_secret` of a confidential client is returned only by `create` and `rotate-secret`. Store it in a secret manager or the host's environment variables immediately. The old secret stops working at once on rotation. Never put it in client-side code, the repo, or logs.
- Redirect URIs must match exactly: `https`, or `http` on `localhost`/`127.0.0.1`/`[::1]` when localhost access is enabled. No fragments, credentials, or custom schemes. Register only the URIs the app uses.
- At most 100 OAuth clients per project (`OAUTH_CLIENT_LIMIT_REACHED` past that). Run `oauth-client list` before creating more, and reuse or delete a client rather than creating duplicates.
- `--skip-consent` only for first-party confidential clients you control.
- A new branch starts with its parent's clients (same IDs and secrets). Rotate secrets on branches that must differ.
## 3. Build the login and consent pages
Both pages receive the signed authorization query. Use `@neon/auth` 0.8.0 or later: the client forwards that query (`oauth_query`) for you. There is no `auth.oauth.resume()` or `getConsentRequest()` helper; do not call or write one, and do not build consent URLs by hand.
```tsx
// lib/auth/client.ts
import { createAuthClient } from "@neon/auth";
export const authClient = createAuthClient(process.env.NEXT_PUBLIC_NEON_AUTH_URL!);
```
Login page. Existing sign-in calls (`signIn.email`, `signIn.social`) carry the query automatically. On every load, including the return from a social sign-in, resume if the user already has a session:
```tsx
const { data } = await authClient.getSession();
if (data?.user) {
const { error } = await authClient.oauth2.continue({ selected: true });
if (error) showError("This sign-in link expired. Go back to the app and try again.");
}
```
`continue` navigates to the consent page or back to the client; a 400 means the link expired. After `signIn.email`, skip your own redirect when `data.redirect` is true.
Consent page. Show the client name, the redirect URI hosts, and the requested `scope` and `resource` (query parameters), and warn when every redirect URI is loopback:
```tsx
const params = new URLSearchParams(window.location.search);
const { data: client } = await authClient.oauth2.publicClient({
query: { client_id: params.get("client_id") ?? "" },
});
// Allow / Deny buttons:
await authClient.oauth2.consent({ accept }); // navigates the browser itself; do not redirect again
```
`publicClient` and `consent` need a signed-in user. Send `Content-Security-Policy: frame-ancestors 'none'` on both pages.
## 4. Protect an MCP server
The user identity is the token's `sub`. Never trust a user id from tool arguments.
Verify `iss` (the exact Auth URL of the branch) and `aud` (the exact MCP server URL) as well as the signature. All branches of a project share signing keys, so the signature alone does not identify the branch. `@neon/oauth` 0.3.0 or later (beta) does all three.
```bash
npm install @neon/oauth @modelcontextprotocol/sdk hono @hono/mcp
```
On a Neon Function, the default export is a Hono app (see the `neon-functions` skill, [references/mcp.md](https://neon.com/docs/ai/skills/neon-functions/references/mcp.md)):
```typescript
import { Hono } from "hono";
import { StreamableHTTPTransport } from "@hono/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { createMcpAuth } from "@neon/oauth/mcp";
import { honoMcp, type McpAuthVariables } from "@neon/oauth/mcp/hono";
const mcpAuth = createMcpAuth({
baseUrl: process.env.NEON_AUTH_BASE_URL!, // the branch's Auth URL
resource: process.env.MCP_RESOURCE!, // exactly the --mcp-resource value
});
const app = new Hono<McpAuthVariables>();
app.use(honoMcp(mcpAuth, { path: "/mcp" })); // metadata routes + bearer guard
app.all("/mcp", async (c) => {
const userId = c.get("auth").sub; // verified identity; scope every query by it
const server = new McpServer({ name: "my-mcp", version: "1.0.0" });
// register tools that close over userId
const transport = new StreamableHTTPTransport({ sessionIdGenerator: undefined });
await server.connect(transport);
return transport.handleRequest(c);
});
export default app;
```
- Stateless: build the server and transport per request.
- `c.get("auth")` is the verified result (`sub`, `clientId`, `scopes`, `claims`); `c.get("authInfo")` is the MCP SDK `AuthInfo`. Express, Next.js, and `node:http` adapters exist (`@neon/oauth/mcp/express`, `/next`, `/node`).
- Set `NEON_AUTH_BASE_URL` and `MCP_RESOURCE` through the Function's `env` in `neon.ts`, and deploy with `neon deploy` (or `neon functions deploy <name> --src <file>`).
- Known gaps: a request with no token gets a challenge with `error="invalid_token"` rather than a bare RFC 6750 challenge, and `/mcp` has no CORS or `OPTIONS` handling, so browser-based MCP clients need CORS added by you.
- Without the SDK, use `jose` against the issuer's JWKS with the same `iss` and `aud` checks. See the docs.
## 5. Endpoints and discovery
- Issuer = the branch's Auth URL, e.g. `https://ep-example.neonauth.us-east-1.aws.neon.tech/neondb/auth`. Copy it from the Console or `base_url` from `GET .../auth`; do not construct it. It differs per branch, so keep it in per-branch config.
- Authorization server metadata: `<issuer>/.well-known/oauth-authorization-server` (also `<issuer>/.well-known/openid-configuration`). It lists the authorize, token, and userinfo endpoints, so read them from there.
- JWKS: `<issuer>/.well-known/jwks.json`. Userinfo: `<issuer>/oauth2/userinfo`.
- The MCP server serves protected resource metadata (RFC 9728); `honoMcp` does this.
- Clients must send `resource` on both the authorize and token requests, or the token is opaque and cannot be verified. Access tokens are EdDSA JWTs valid for one hour. Scopes are fixed: `openid`, `profile`, `email`, `offline_access`. Grants are `authorization_code` and `refresh_token`; there is no `client_credentials`.
## 6. Verify
1. `neon neon-auth config oauth-server get` shows `enabled`, both pages, and the resource.
2. `curl <issuer>/.well-known/oauth-authorization-server`: `issuer` equals the Auth URL.
3. `curl -i <mcp-url>` without a token: 401 whose `WWW-Authenticate` points to the protected resource metadata, and that metadata names the issuer.
4. Run the real flow with MCP Inspector (`npx @modelcontextprotocol/inspector`, Streamable HTTP, the MCP URL) or an MCP client such as Cursor or Claude. Expect: redirect to your login page, then your consent page, then a token, then a successful tool call.
5. Confirm a tool returns data for the signed-in user only, and that a token for another resource or branch is rejected.
6. For a managed client, run authorize with PKCE and `resource`, then exchange the code at the token endpoint.
Report any step you could not run.
## Do NOT
- Do not move to self-managed Better Auth or the Better Auth MCP plugin for this. Managed supports it.
- Do not confuse this with `neon neon-auth oauth-provider` (social login) or Generic OAuth.
- Do not call `auth.oauth.resume()`, `getConsentRequest()`, or any resume helper. Use `oauth2.continue`, `oauth2.publicClient`, and `oauth2.consent`.
- Do not put client secrets, or Neon API keys, in browser or mobile code.
- Do not skip `iss` and `aud` checks, or trust a user id from tool input instead of `sub`.
- Do not enable dynamic client registration or `--skip-consent` for third-party or public clients.
- Do not list the MCP server URL under resources instead of `--mcp-resource`.
references/self-managed.md
# Self-managed Better Auth
Use this page only after `SKILL.md` routed here: a required feature is outside Managed Auth, and the installed Better Auth version documents that flow. If that check fails, keep the current identity.
## Keep existing Better Auth
If the app already runs Better Auth, keep that server, its clients, users, and sessions. It works with Lakebase Postgres, Functions, Object Storage, and the AI Gateway. Do not migrate it to Managed Auth unless the user asks.
## New self-managed server
Host it on the existing app (Vercel route handlers, or similar) when that host already serves `/api/auth`. Use a Neon Function when the auth server should sit next to Postgres, for example. Function hosting follows the `neon-functions` skill (region, claim, `neon.ts`, `neon deploy --env <file>`).
Keep Lakebase Postgres as the auth database. Use `better-auth` and `better-auth/client`. Fetch upstream docs for the **installed** version:
- https://better-auth.com/docs/installation
- https://better-auth.com/docs/concepts/client
- https://better-auth.com/docs/concepts/plugins
Do not pass `plugins` into `@neon/auth`. Replacing only the client package while Managed Auth is still the backend does not add plugins.
The OAuth provider and MCP OAuth (Cursor, Claude, and similar clients self-authorizing) are supported on Managed Auth: [oauth-server.md](oauth-server.md). They are not a reason to self-manage.
Function JWT verification, CORS, and direct browser calls: `neon-functions` and https://neon.com/docs/compute/functions/authentication.md.
There is no documented universal import from Managed `neon_auth` into a self-managed Better Auth schema. Inventory users, credentials, sessions, memberships, and application foreign keys before changing existing state. Agree a cutover plan with the owner. Do not promise drop-in session continuity.
SKILL.md
---
name: neon-auth
description: >-
Add authentication to a new app. Use for "add auth", "add login", Neon Auth
(Managed Better Auth), identity routing, sign-up, sign-in, password reset,
email OTP, magic links, organizations, phone OTP, OAuth, OAuth server for MCP
or third-party OAuth clients, passkeys, MFA,
trusted domains, invalid domain, and @neon/auth. No existing identity:
default to Managed Better Auth. Keep working Better Auth, Clerk, Supabase
Auth, or another IdP. User asked to migrate from Supabase Auth: Managed
Better Auth. A required plugin outside Managed support: self-managed Better
Auth on a Neon Function or the existing app host. Also use for auth APIs in
@neon/neon-js.
metadata:
parent: neon
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-auth
---
**FIRST**: Use the parent `neon` skill for a Neon overview, getting started with Neon, Neon development best practices, and more.
If the `neon` skill is not installed, fetch it from https://neon.com/docs/ai/skills/neon/SKILL.md or install it with:
```bash
neon skills -s neon -y
```
# Neon Auth
Neon Auth is Managed Better Auth: users, sessions, and auth config live in the `neon_auth` schema on the branch's Lakebase Postgres, and auth state branches with the database. The client API is the Better Auth method set (`signIn.email`, `signIn.social`, `getSession`) through `@neon/auth`. That wrapper is not a drop-in for bare `better-auth/client`: it pins the plugin list and adds Neon-specific OAuth verifier, iframe popup, and JWT handling. Stay on the wrapper while Auth is managed.
This skill chooses identity, then implements Managed Better Auth. It does not replace a working auth server in order to use Postgres, Functions, Object Storage, or the AI Gateway.
## When to Use
Inspect existing identity and the required login features before provisioning. A supplied `DATABASE_URL` is not a reason to change identity. Adding a Neon Function is not a reason to change identity.
| Situation | What to do |
| --- | --- |
| No existing auth | Default to Managed Better Auth. [Managed setup](#managed-setup), then [references/managed-auth.md](references/managed-auth.md). |
| Needs a feature Managed does not offer | Self-managed Better Auth on the existing app host (Vercel or similar) or a Neon Function. Keep Lakebase Postgres. Confirm the **installed** Better Auth version documents that exact flow before recommending the move. If support stays unresolved, keep the current identity. [references/self-managed.md](references/self-managed.md). |
| Already has Better Auth | Keep it. It works with the other Neon primitives. Migrate to Managed only if the user asks. |
| User asked to migrate from Supabase Auth | Managed Better Auth. [Supabase Auth](#supabase-auth). Moving only Postgres or adding a Function keeps Supabase Auth. |
| Clerk, Auth.js, Supabase Auth, or another working IdP | Keep it unless the user asks to migrate. |
Google, GitHub, Microsoft, Vercel, and Apple social OAuth are offered on Managed Auth. They are not a reason to leave Managed Auth. Microsoft and Apple need your own credentials: [Apple and Microsoft OAuth](#apple-and-microsoft-oauth). Making Neon Auth the OAuth server for your own MCP server or third-party OAuth clients is supported: [references/oauth-server.md](references/oauth-server.md). Other OAuth providers, generic OAuth, MFA, passkeys, API keys, SSO, custom plugins, hooks, and custom JWT claims are the [plugin matrix](#plugin-support) check.
Before enabling Managed Auth, confirm the project is on AWS and does not use IP Allow or Private Networking. Leave those protections in place.
Configure supported Managed plugins through Neon (Console, API, or `neon neon-auth`), not by passing `plugins` into `@neon/auth`. Enabling `auth: true` is not implementing login.
## What It Does
- **Managed identity in Postgres** — users and sessions in `neon_auth`, queryable with SQL, compatible with RLS.
- **Auth emails without an app mailer** — verification, email OTP, magic links, and password reset. Getting started uses shared SMTP (`auth@mail.myneon.app`). You do not add Resend or SendGrid to implement login. Production needs custom SMTP: https://neon.com/docs/auth/production-checklist.md
- **Branches with the database** — each branch has its own Auth URL and isolated auth state.
- **Better Auth client methods via the Neon SDK** — `@neon/auth` (auth only) or `@neon/neon-js/auth` (combined SDK). Optional UI: Better Auth UI (`@better-auth-ui/react` with its shadcn/ui components).
- **Fixed plugin set** — the Managed client does not accept a `plugins` option. See [plugin support](#plugin-support).
## Availability
Managed Better Auth is generally available. AWS regions only. It cannot be enabled on a project with IP Allow or Private Networking.
Organization is separately Partial / Beta. Hosting self-managed Better Auth in a Neon Function follows Functions availability and claim rules; use the `neon-functions` skill for that host. An unclaimed project that can enable Auth still cannot use Functions until claim.
## Managed setup
Merge Auth into the existing `neon.ts`. Do not replace other fields:
```typescript
import { defineConfig } from "@neon/config/v1";
export default defineConfig({
auth: true,
});
```
```bash
neon deploy
neon neon-auth status
```
If Function env in that config reads `process.env`, use `neon deploy --env <file>` as the parent skill describes. The manual service command is `neon neon-auth enable`; do not run both enable and deploy as redundant required steps when `neon.ts` already declares `auth: true`.
Then implement login: [references/managed-auth.md](references/managed-auth.md). To make Neon Auth the OAuth server for an MCP server or OAuth clients, continue to [references/oauth-server.md](references/oauth-server.md).
Claimable projects: follow the parent Claimable path, then `auth: true` and `neon deploy` when login is requested and no existing provider should be preserved.
## Supabase Auth
When the user asked to migrate login from Supabase Auth, recommend Managed Better Auth and follow https://neon.com/docs/auth/migrate/from-supabase.md. Moving only Postgres or adding a Function is not that request: keep Supabase Auth.
`SupabaseAuthAdapter()` keeps method shapes such as `signInWithPassword` and `signInWithOAuth`. Those calls are not interchangeable with default Better Auth examples (`signIn.email`). Keep an existing adapter caller on that API.
Inventory the auth methods and database calls actually used:
- Password hashes cannot transfer. Users create new accounts or sign in with OAuth.
- Do not promise unchanged user IDs, sessions, or account linking. Plan application foreign keys with the owner.
- `updateUser()` cannot change email or password on Managed Auth. Email verification needs application UI (codes work on shared SMTP; links need custom SMTP).
- The migration guide lists Supabase phone/SMS/WhatsApp, SAML, and Web3 as unsupported on Managed Auth. Confirm the **installed** Better Auth version if the user still needs that exact flow; if support stays unresolved, keep Supabase Auth and stop the auth cutover. That page's "no phone auth" claim is about Supabase phone sign-in, not the constrained Managed Phone Number plugin (existing users link a number).
- `@supabase/supabase-js` used only for Auth does not justify enabling the Data API. Keep Data API only for existing PostgREST / Supabase database-client queries.
## Verification
Managed path: sign-up, sign-in, sign-out, session restoration after reload, and protected access, including error and loading states. Exercise email verification (code on shared SMTP) when it is on. Report any flow that remains unverified.
A required plugin on the self-managed path is verified in that app's Better Auth setup, not as a Managed flow.
## Plugin support
Checked 2026-10-30 against https://neon.com/docs/auth/guides/plugins.md, https://neon.com/docs/auth/guides/plugins/oauth-provider.md, https://neon.com/docs/auth/roadmap.md, and the `@neon/auth` client plugin list. Re-fetch those pages if this skill may be stale. An unlisted upstream plugin needs a live check; do not treat absence from this table as a dated roadmap item.
"Not exposed" means the Managed SDK/UI contract. It is not a claim that every raw server request was tested.
| Feature | Managed Auth | Boundary |
| --- | --- | --- |
| Email/password | Supported | `signUp.email`, `signIn.email` |
| Social OAuth (Google, GitHub, Microsoft, Vercel, Apple) | Supported | `signIn.social`. Shared Google credentials are for development; production and GitHub/Vercel need your own OAuth apps. Microsoft and Apple always need your own ([details](#apple-and-microsoft-oauth)). https://neon.com/docs/auth/guides/setup-oauth.md |
| Admin | Supported | Admin session required. Plugin customization is on the roadmap. |
| Email OTP | Supported | Managed delivery. `emailOtp.sendVerificationOtp`, `signIn.emailOtp`. |
| Magic Link | Supported | Enable on the branch (off by default). `signIn.magicLink`. |
| Organization | Partial, Beta | Members, invitations, owner/admin/member. No Teams, server hooks, custom roles/permissions, or dynamic access control. Emailed invitations: [managed-auth.md](references/managed-auth.md#organization-invitations). |
| JWT | Supported | EdDSA (Ed25519), 15-minute expiry, no custom claims. Default client: `.token()` then `data.token`. `SupabaseAuthAdapter()`: `getSession()` then `data.session.access_token` (no `.token()`). |
| Open API | Supported | Server routes `/reference` and `/open-api/generate-schema`. |
| Phone Number | Supported with constraints | Browser client: existing users link a number, then sign in; no phone-first signup; own SMS webhook; custom UI. Next.js `auth.handler()` forwards the catch-all path, including phone OTP. A missing `auth.phoneNumber` server method is a missing typed helper, not a proxy rejection. https://neon.com/docs/auth/guides/plugins/phone-number.md |
| MFA / Two-Factor | Roadmap | Unavailable on Managed Auth. If required: [self-managed.md](references/self-managed.md), after confirming the installed Better Auth version. |
| Passkey, API Key, Generic OAuth, One Tap, Multi Session | Not exposed by Managed SDK/UI | If required: [self-managed.md](references/self-managed.md). Generic OAuth is not Google/GitHub/Microsoft/Vercel/Apple social sign-in. |
| OAuth Provider (OAuth server, MCP auth) | Supported (beta) | Neon Auth is the OAuth 2.1 / OIDC server for your MCP server or third-party OAuth clients. You host the login and consent pages; no client credentials grant. See [references/oauth-server.md](references/oauth-server.md). |
| SSO / SAML | Not listed or exposed | If required: [self-managed.md](references/self-managed.md), after confirming the installed Better Auth version. |
The default Managed client method is `getAnonymousToken()`. That JWT is a Neon anonymous Data API token. It is not Better Auth's Anonymous-account plugin (`signIn.anonymous`). `anonymousTokenClient()` is the SDK plugin factory, not a method on the public client. Do not call it, and do not call `getAnonymousToken()` on `SupabaseAuthAdapter()`.
Trusted domains and webhooks are Neon settings, not installable Better Auth plugins.
## Apple and Microsoft OAuth
Both providers reject shared credentials; add them with your own via `neon neon-auth oauth-provider add|update` (Console and API work too). A multi-line secret goes in a file with `--oauth-client-secret-file`, not inline.
- **Apple**: `client_id` is the Services ID, `client_secret` is the full `.p8` private key. Also pass `--apple-team-id` and `--apple-key-id` (10 characters). Neon Auth signs the client-secret JWT itself, so there is nothing to rotate. Rotating the key needs the new `--apple-key-id` in the same update. The return URL must be HTTPS (`https://<auth host>/<db>/auth/callback/apple`); Apple rejects localhost, so test through a tunnel or a deployed preview.
- **Microsoft**: `client_id` and `client_secret` from the Entra app registration. `--microsoft-tenant-id` is optional: `common` (default), `organizations`, `consumers`, a tenant GUID, or a domain. The redirect URI is `<base_url>/callback/microsoft`.
- **Microsoft email verification**: an email counts as verified only when the ID token carries `xms_edov` = true and `acct` = 0. Add `xms_edov` and `acct` as optional ID-token claims in Entra. Without them, a same-email existing user gets `account_not_linked`, `link-social` fails with `unable_to_link_account`, and new users stay unverified.
## Trusted domains
Auth redirects only to origins on its allowlist. `invalid domain` means the app origin is missing. Include the scheme, omit a trailing slash, register production and preview origins before pointing users at them, and target the correct branch:
```bash
neon neon-auth domain add https://app.example.com
neon neon-auth domain list
neon neon-auth domain delete https://old.example.com
```
Localhost ports are pre-approved by default. An existing project can have that off: `neon neon-auth domain allow-localhost get|enable|disable`. Docs: https://neon.com/docs/auth/guides/configure-domains.md
OAuth provider redirect is `{NEON_AUTH_BASE_URL}/callback/{provider}` (the Auth URL includes its path). `callbackURL` on `signIn.social` is the later app landing origin and must be trusted.
The Managed SDK handles iframe OAuth popup and `neon_auth_session_verifier`. Keep the wrapper, callback route, and middleware. Do not reimplement that flow, and do not promise third-party cookies in every browser.
## Functions and Data API
A Function authenticates whoever already signs the user in. Do not switch identity to call a Function. Verify the token in the `neon-functions` skill and https://neon.com/docs/compute/functions/authentication.md.
Managed Auth: injected `NEON_AUTH_JWKS_URL`, issuer from `NEON_AUTH_BASE_URL`. Token: default client `.token()` then `data.token`; `SupabaseAuthAdapter()` `getSession()` then `data.session.access_token`. A valid token is not permission to read another user's rows. Sign-out ends the browser session; do not claim it immediately revokes an already-issued JWT.
Data API identity: [references/managed-auth.md](references/managed-auth.md). New apps query Postgres from Functions or existing handlers, not the Data API.