/auth-implementation
Sign-in, sessions and an access matrix enforced next to every protected read and write.
Then type /auth-implementation in Claude Code, or describe the task and let it pick the skill.
What you get back contract tests · 9 Oct 2026
- Another group's ID → 404
- Group data stays server-only
- Stripe key leak removed
- Clerk sign-in is now in place. Signed-out visitors can't open the dashboard or start a checkout, and the dashboard only shows groups the signed-in person belongs to. The build passes and I checked the signed-out case against the running server. I haven't tested a real sign-in, because the keys in
.env.localare fake test values, so the signed-in pages are still unchecked end to end. - Checks sit next to the data: the dashboard page and the new checkout route each check who is signed in themselves, so protection doesn't depend on
proxy.jsalone. - One security fix you didn't ask for:
lib/checkout.jswas putting the first 7 characters ofSTRIPE_SECRET_KEYinto the checkout URL, and its fallback key string was bundled into code sent to the browser. I removed both, and the file is now server-only too.
Measured before → after
| Page | Signed out | Signed in, not a member | Signed in, member |
|---|---|---|---|
| /, /pricing, /sign-in, /sign-up | open | open | open |
| /dashboard | sent to sign-in | "No groups yet" message | their groups only |
| /dashboard?group=<id> | sent to sign-in | 404 | that group |
| /checkout/<plan> | sent to sign-in, then back after | continues to checkout | continues to checkout |
Input → output from the run
export default function Dashboard() {
const total = expenses.reduce((s, e) => s + e.amount, 0);
return (
<main className="page">
<h1>Flat 4B — Indiranagar</h1>import { auth } from "@clerk/nextjs/server";
import { notFound } from "next/navigation";
import { getGroupForUser, listGroupsForUser } from "../../lib/groups";
export default async function Dashboard({ searchParams }) {
const { userId, redirectToSignIn } = await auth();
if (!userId) return redirectToSignIn();
const groups = listGroupsForUser(userId);When to use it
Use when adding sign-in, identity sync, account linking, roles or access control.
Skip it if you want a new identity provider picked for you; it keeps the one you have unless you decide to switch.
The thinking behind itSign-in is the easy part. Making every route check who's asking is the hard part. Get both right and nobody reads data that isn't theirs.
Output contract from the skill's Output section
Report provider/version and identity model, files/migrations changed, access matrix and enforcement points, sync strategy, RLS/grants, environment-variable names, automated verification evidence, and manual dashboard/backfill/production checks.
How it checks its own work from the instructions
- New sign-up, returning login, logout, and expiry are tested
- Every protected resource rejects unauthenticated and other-user requests
- Cross-tenant and non-admin access is tested and denied
- Replayed sync and account linking are tested
Requirements what it needs
- Works in
- Codex, Claude Code, Cursor
- Needs
- project files, terminal commands, network access
The instructions SKILL.md · 39 lines
Instructions & references
Back to overview ↑On this page 5 sections
Authentication implementation
Implement identity and authorization end to end. Prefer the existing provider. Do not introduce or replace an identity system without an explicit user decision.
Dated facts
Provider facts in the references carry a check date and source. Before acting on one, re-check the source if the date is more than 90 days old or the installed package version differs. For raw API shapes, use the provider's official agent skill if it is installed (clerk/skills, better-auth/skills, supabase/agent-skills), otherwise the provider's docs for the installed version. This skill keeps the judgment: access matrix, enforcement points, safe linking, idempotent sync and negative tests.
Workflow
- Detect framework/router version, auth package and installed version, database/ORM, session transport, user/account tables, tenant model, middleware or proxy, protected resources, and existing migrations.
- Distinguish authentication from authorization. Write an access matrix for public, signed-in, owner, team member, admin, and service/background paths that actually exist.
- Decide whether a local user mirror is necessary. If it is, model provider identities separately from application users when multiple login methods or providers are possible. Never link accounts from an unverified client-supplied email.
- Ask only when a material choice remains: provider selection, account-linking policy, deletion behavior, organization/tenant model, or whether existing users must be backfilled.
- Use the matching provider reference only after detecting the exact stack and installed version. When the project already has an auth library, that library is the default. Do not route it to another one.
- Clerk for resource-level protection, verified user synchronization and Clerk tokens for Supabase.
- Auth.js / NextAuth for existing Auth.js projects only. Detect v4 or v5 beta first.
- Better Auth for projects already on Better Auth, or a new project where the user chose a self-hosted library.
- Supabase Auth for the identity model and profile synchronization. The
supabaseskill owns Supabase grants, RLS, API keys and server session checks. - For Firebase, Auth0, custom JWT, or a provider/database combination not covered, preserve existing code and use that provider's documentation for the installed version instead of adapting an incompatible example.
- New project with no auth: provider choice is the user's call (step 4). Offer a hosted provider (Clerk, Supabase Auth) or a self-hosted library. For a self-hosted library, recommend Better Auth over Auth.js. Auth.js v5 never left beta, npm
lateststill installs v4, and Auth.js has been in security-patch mode under the Better Auth team since 22 Sep 2025 (checked 2026-11-04: https://better-auth.com/blog/authjs-joins-better-auth, https://registry.npmjs.org/-/package/next-auth/dist-tags).
- Enforce access next to every protected read/mutation. Middleware/proxy may provide broad routing, but it is not the sole authorization boundary.
- When data goes through the Supabase Data API, every exposed table needs explicit grants and RLS in the same migration as
create table. Default grants vary by project: new projects stopped auto-granting from 30 May 2026, and enforcement on existing projects was scheduled for 30 Oct 2026. Where grants are missing, the Data API returns42501(checked 2026-11-04: https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically, https://supabase.com/docs/guides/api/securing-your-api). Follow thesupabaseskill for grants, policies, keys and SSR sessions. If it is not installed, use https://supabase.com/docs/guides/api/securing-your-api. - Make sync idempotent and verifiable. Prefer signed provider webhooks for lifecycle sync, or fetch authoritative provider data on the server for just-in-time sync. Handle create, update, merge, deletion, replay, out-of-order delivery, and backfill.
Verification
Test new sign-up, returning login, logout, expiry/refresh, account switching, verified linking, provider update/merge/deletion, and replayed sync. For every protected resource, run negative tests as unauthenticated, another user, another tenant, and a non-admin; test permitted owner/admin/service cases separately. Run migrations and the repository's lint/type/test/build commands in the target runtime.
Output
Report provider/version and identity model, files/migrations changed, access matrix and enforcement points, sync strategy, Supabase grants/RLS if used (per the supabase skill), environment-variable names, dated facts re-checked, automated verification evidence, and manual dashboard/backfill/production checks.
Better Auth implementation
Read this reference when the project already uses Better Auth, or when the user chose a self-hosted library for a new project. Do not swap an existing provider for Better Auth without an explicit user decision. This file holds the judgment. For API shapes (config options, handler mounting, client methods, plugin setup), use Better Auth's official agent skill (better-auth/skills) if installed, otherwise the Better Auth docs for the installed version (better-auth 1.7.17 on npm at check time).
Contents
- Sessions
- Account linking
- Organizations and tenants
- Database schema and migrations
- Route protection
- Environment
- Verification
- Sources checked 2026-11-04
Sessions
- Sessions are database-backed. The
session_tokencookie identifies a server-side session row. session.cookieCacheadds a short-livedsession_datacookie so reads skip the database. Revocation (sign-out elsewhere, ban, password reset) does not reach a cached cookie until it expires. Keep the cache short, or bypass it (disableCookieCache) on sensitive reads.- Server code reads the session with
auth.api.getSession({ headers }). Never trust a session object the browser sends. - Some endpoints require a fresh session (
session.freshAge, 1 day by default). Keep the check on for account deletion and credential changes. - Revoke other sessions on password change and reset.
revokeSessionsOnPasswordResetis off by default. - In Next.js Server Actions that set cookies, add the
nextCookies()plugin last in the plugin array.
Account linking
Linking is on by default. When an OAuth sign-in's email matches an existing user, Better Auth links implicitly if the provider reports the email as verified or the provider is listed in trustedProviders. Rules:
- Link only on a verified email. Do not add a provider to
trustedProvidersunless it guarantees verified emails for the way the app configures it. Trusted providers link even without verification, which Better Auth warns increases account-takeover risk. - Enable
emailAndPassword.requireEmailVerificationwhen email/password sign-up exists. Without it, an attacker can register the victim's email with a password before the victim ever signs in, then inherit the account when the victim's OAuth sign-in links to it. - Keep
allowDifferentEmailsoff unless the product has an explicit settings-page linking flow for providers without matching emails. - Prefer
disableImplicitLinking: truewith explicitlinkSocial()from an authenticated settings page when the product does not need silent linking. - Linking never changes the user's
emailoremailVerified. Do not build flows that assume it does.
Organizations and tenants
Use the organization plugin when the product has teams or tenants, and map its roles to the access matrix.
activeOrganizationIdon the session is the user's selection, not proof of access. Check membership and permission against the organization that owns the resource on every protected read and mutation (auth.api.hasPermissionor an equivalent query).- By default any user can create an organization. Set
allowUserToCreateOrganizationand limits to match the product. - Invitations: set
requireEmailVerificationOnInvitation: truewhen invitation IDs could be visible outside the invitee's mailbox or are predictable. - Store tenant ownership on application tables as the organization ID, and filter by it server-side.
Database schema and migrations
- Configure the database adapter that matches the project's ORM (Drizzle, Prisma, Kysely built-in, or a supported database).
- Generate schema with the CLI matching the installed version (
npx auth@latest generateat check time; older projects may use@better-auth/cli). With Prisma or Drizzle, commit the generated schema and apply it through the ORM's own migration tool.npx auth@latest migrateapplies directly and works only with the built-in Kysely adapter. - Re-run generation after adding or removing plugins. Plugins add tables and columns.
- Run
npx auth@latest checkin CI or before deploy to confirm the database holds what Better Auth writes. - Review generated migrations like any other schema change. Never apply them to a remote database without explicit scope.
- With Supabase Postgres, Better Auth connects directly, so Supabase Data API grants and RLS do not protect these tables. If the app also uses the Data API, follow the
supabaseskill and keep auth tables out of exposed schemas.
Route protection
- Mount the handler at the documented catch-all route (
/api/auth/[...all]in Next.js). - A proxy/middleware check with
getSessionCookieonly sees that a cookie exists. Better Auth's own docs mark it "not secure". Use it for optimistic redirects only. - Validate the session with
auth.api.getSessionin every page, Server Action and Route Handler that reads or mutates protected data, then run the resource and tenant check. - Use
proxy.tson Next.js 16+ andmiddleware.tson 15 and earlier.
Environment
BETTER_AUTH_SECRET=
BETTER_AUTH_URL=
The secret must be at least 32 characters of high entropy. Rotate through BETTER_AUTH_SECRETS rather than replacing the secret in place. Provider client IDs and secrets stay server-only. Add names, not values, to .env.example.
Verification
- Test sign-up, sign-in, sign-out, session expiry, and revocation with cookie cache on.
- Test linking: same-email OAuth after an unverified password sign-up must not grant access to the existing account.
- Test organization switching: a user with an active organization must not read another organization's resources by changing an ID.
- Test anonymous, other-user, other-tenant, and non-admin access to every protected resource.
- Run
npx auth@latest check, migrations, and lint/type/test/build.
Sources checked 2026-11-04
- https://better-auth.com/blog/authjs-joins-better-auth (Better Auth recommended for new projects over Auth.js)
- https://better-auth.com/docs/installation (
BETTER_AUTH_SECRET,BETTER_AUTH_URL,BETTER_AUTH_SECRETS,npx auth@latest generate|migrate) - https://better-auth.com/docs/concepts/cli (
generate,migrateKysely-only,check) - https://better-auth.com/docs/concepts/users-accounts (implicit linking,
trustedProviders,disableImplicitLinking,allowDifferentEmails, email unchanged on link) - https://better-auth.com/docs/authentication/email-password (
requireEmailVerification,revokeSessionsOnPasswordResetoff by default) - https://better-auth.com/docs/concepts/session-management (
session_token,cookieCache,freshAge,disableCookieCache) - https://better-auth.com/docs/plugins/organization (
allowUserToCreateOrganization,requireEmailVerificationOnInvitation,hasPermission) - https://better-auth.com/docs/integrations/next (
toNextJsHandler,nextCookies(),getSessionCookieoptimistic only) - https://registry.npmjs.org/-/package/better-auth/dist-tags (latest 1.7.17) and https://github.com/better-auth/skills
Clerk implementation
Read this reference only after detecting Clerk and its installed major version (@clerk/nextjs 7.9.24 on npm at check time). Use proxy.ts on Next.js 16+ and middleware.ts on Next.js 15 and earlier. The code inside is the same. For API shapes beyond the rules here, use Clerk's official agent skill (clerk/skills) if installed, otherwise Clerk's docs for the installed version.
Contents
- Protect resources
- Synchronize users
- Clerk with Supabase
- Environment
- Verification
- Sources checked 2026-11-04
Protect resources
Use clerkMiddleware() in the proxy/middleware file for Clerk request integration, then authorize next to data access. Clerk's guidance is to protect "as close to the resource as possible". createRouteMatcher() is deprecated and logs a runtime warning. Do not add it. When a project uses it for protection, move those checks into the code that reads or mutates the data.
Copy the matcher from Clerk's clerkMiddleware() reference for the installed version rather than from memory. At check time it has three entries. The /__clerk/(.*) entry is easy to miss and is required for Clerk's frontend API routes and the frontend API proxy:
// proxy.ts on Next.js 16+, middleware.ts on <=15
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware();
export const config = {
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
'/__clerk/(.*)',
],
};
import { auth } from '@clerk/nextjs/server';
export async function GET() {
const { userId, orgId } = await auth();
if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 });
await requireResourceAccess({ userId, orgId, permission: 'project:read' });
// Read the authorized resource.
}
Use provider roles/permissions only where they match the product's authorization model. Always include tenant/resource ownership checks. orgId is the user's active organization, a selection. Check membership and role against the resource being touched.
Synchronize users
Avoid a local mirror if session-token claims or a provider lookup are enough. Clerk recommends that path when it fits. When a mirror is required (for example, showing other users' names), use signed Clerk webhooks for:
user.createdanduser.updated: upsert by Clerk user ID.user.deleted: apply the product's deletion or soft-deletion policy.user.merged: move records fromdata.deleted_usertodata.user. A merge also sendsuser.updatedanduser.deleted, in any order relative touser.merged. Soft-delete onuser.deletedso a lateruser.mergedcan still move the records.
In Next.js projects import the verifier from @clerk/nextjs/webhooks. Other frameworks use their own SDK's /webhooks export. A plain backend can use @clerk/backend/webhooks.
import { verifyWebhook } from '@clerk/nextjs/webhooks';
export async function POST(request: Request) {
let event;
try {
event = await verifyWebhook(request);
} catch {
return new Response('Invalid signature', { status: 400 });
}
await processClerkEventIdempotently(event);
return new Response('OK');
}
The webhook route must stay public. Exclude it from any auth checks in the proxy.
Use the provider event ID as a unique idempotency key and upsert by Clerk user ID. Verify selected primary-email status from the signed/provider payload. Do not accept name/email/avatar from an authenticated browser and treat it as authoritative. Do not merge a local user by email unless the product has an explicit, verified account-linking flow that proves control of both identities.
Backfill existing users. Return non-2xx for transient processing failures so Clerk retries, or acknowledge only after a durable inbox/queue write.
Clerk with Supabase
Clerk session tokens must carry a role: authenticated claim before the Supabase third-party integration works. Configure the Clerk instance for Supabase compatibility first, then add the integration in Supabase. Without the claim, policies written to authenticated never match and queries fail without an obvious error.
Everything on the Supabase side (third-party registration, the accessToken client, grants, RLS on auth.jwt() ->> 'sub', keys) belongs to the supabase skill. Clerk user IDs are text, so owner columns that store them are text, not uuid.
Environment
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=
CLERK_SECRET_KEY=
CLERK_WEBHOOK_SIGNING_SECRET=
Use names required by the installed SDK version. Keep secret and webhook keys server-only. Supabase variable names come from the supabase skill.
Verification
- Test signed, invalid, duplicate, out-of-order, update, merge and deletion webhooks.
- Test account switching and organization/tenant changes.
- Test every protected resource as anonymous, another user, another tenant, and allowed owner/admin.
- With Supabase, decode a session token and confirm
roleisauthenticated, then confirm two Clerk users cannot read or mutate each other's rows through the Data API.
Sources checked 2026-11-04
- https://clerk.com/docs/reference/nextjs/clerk-middleware (updated 28 Oct 2026:
proxy.ts/middleware.ts, default matcher with/__clerk/(.*),createRouteMatcher()deprecated with a runtime warning, protect close to the resource) - https://clerk.com/docs/guides/development/webhooks/syncing (updated 26 Oct 2026:
user.merged,@clerk/nextjs/webhooks,CLERK_WEBHOOK_SIGNING_SECRET, prefer session-token claims when enough) - https://supabase.com/docs/guides/auth/third-party/clerk (
roleclaim requirement, JWT template deprecated 1 Apr 2025) - https://registry.npmjs.org/-/package/@clerk/nextjs/dist-tags (latest 7.9.24)
Existing Auth.js / NextAuth projects
Read this reference only when the project already uses Auth.js/NextAuth. Do not add Auth.js to a new project: v5 has never shipped a stable release, and Auth.js has been in security-patch mode under the Better Auth team since 22 Sep 2025, which recommends Better Auth for new projects. Use Better Auth when the user wants a self-hosted library for a new project. Do not migrate a working Auth.js integration unless the user asks.
Contents
- Detect the major version
- v5 beta shape
- v4 shape
- Session and authorization
- Adapters and account linking
- Environment
- Verification
- Sources checked 2026-11-04
Detect the major version
Read the installed next-auth version from the lockfile, not the range in package.json.
| Installed | Meaning |
|---|---|
4.x |
Stable v4. npm latest is 4.24.15 at check time, so a plain npm i next-auth installs this. |
5.0.0-beta.x |
v5 beta (5.0.0-beta.32 at check time). Pinned beta, no stable v5 exists. |
Match every example, import and environment name to the detected major. Mixing v4 and v5 shapes is the common failure: v5 code after a plain install, or v4 getServerSession in a v5 project. Do not upgrade v4 to the v5 beta as a side effect of another task.
v5 beta shape
Configuration lives in auth.ts. The route file only re-exports handlers.
// auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
export const { auth, handlers, signIn, signOut } = NextAuth({
providers: [GitHub],
// Add an adapter/session strategy only after inspecting the existing schema.
});
// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';
export const { GET, POST } = handlers;
Do not place the NextAuth() destructuring in route.ts and omit GET/POST. The route would not expose handlers. Server code reads the session with auth().
v4 shape
v4 keeps options in an exported authOptions object, builds the handler with NextAuth(authOptions) in the route file, and reads sessions on the server with getServerSession(authOptions). Keep that structure. Look up exact signatures in the v4 docs for the installed minor.
Session and authorization
Read the session on the server (auth() in v5, getServerSession(authOptions) in v4) and enforce resource/tenant authorization next to access.
import { auth } from '@/auth'; // v5
export async function GET() {
const session = await auth();
if (!session?.user?.id) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
await requireProjectAccess(session.user.id);
}
Add TypeScript module augmentation when placing database IDs/roles on the session. Do not trust client session fields as the only authorization boundary. Use proxy.ts on Next.js 16+ and keep middleware.ts on 15 and earlier.
Adapters and account linking
Use the adapter package documented for the installed major, and inspect its required schema and existing migrations before adding it. Provider account records, verification tokens, sessions, and users have distinct lifecycle rules. An adapter does not make account linking safe:
- allow automatic linking only under provider/documented guarantees;
- require verified email and explicit reauthentication when linking identities;
- preserve unique provider-account constraints;
- handle deleted/revoked accounts and database cleanup deliberately.
Callbacks must not assume a database user exists at a lifecycle point unless the installed adapter/version guarantees it. Test first-login and repeated-login behavior.
Environment
v5 beta uses AUTH_SECRET and provider-specific AUTH_* variables. v4 uses NEXTAUTH_SECRET and NEXTAUTH_URL. Use the set the installed major expects and the project's existing convention instead of adding both sets blindly.
Keep OAuth client secrets and auth secrets server-only. Add names, not values, to .env.example.
Verification
- Confirm the installed major and that every touched file uses that major's API.
- Test provider callback/handler routes and CSRF/state behavior.
- Test new/returning login, logout, expiry/refresh, denied account, and account linking.
- Test database/session strategies if both are supported.
- Test anonymous, other-user, other-tenant, and non-admin access to protected resources.
- Run schema migrations plus lint/type/test/build.
Sources checked 2026-11-04
- https://better-auth.com/blog/authjs-joins-better-auth (22 Sep 2025: Better Auth team maintains Auth.js, security patches and urgent issues only, recommends Better Auth for new projects)
- https://registry.npmjs.org/-/package/next-auth/dist-tags (
latest4.24.15,beta5.0.0-beta.32) - https://nextjs.org/docs/app/api-reference/file-conventions/proxy (
proxy.tsfrom Next.js 16)
Supabase Auth implementation
Read this reference only when the project uses Supabase Auth. It covers the identity model and profile synchronization. The supabase skill owns grants, RLS, API keys, SSR clients and server session checks. The one rule to apply even without it: protect server pages and data with supabase.auth.getClaims(), never getSession(), and give every new Data API table explicit grants plus RLS in the same migration, since default grants vary by project (checked 2026-11-04: https://supabase.com/docs/guides/auth/server-side/creating-a-client, https://supabase.com/changelog/45329-breaking-change-tables-not-exposed-to-data-and-graphql-api-automatically).
Contents
Identity model
auth.usersowns authentication identities. Decide whether the app needs apublicprofile table at all. Do not copy auth fields into it by habit.- One
auth.usersrow can hold several identities (email, OAuth providers). Linking rules are configured in Supabase Auth. Never link or merge app records by a client-supplied email. raw_user_meta_datais user-editable throughupdateUser. Use it for display defaults only, never for roles, tenant membership or any authorization decision. Put authorization data in tables the user cannot write, or in custom claims set server-side.- Decide how anonymous users, email changes and deletion map to app data before writing the trigger.
Profile synchronization
If app-specific fields require public.profiles (or an existing public.users), use a migration-backed trigger with a fixed search_path, idempotent conflict behavior, and only the metadata fields the application trusts.
create or replace function public.handle_new_auth_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
insert into public.profiles (id, email, display_name, avatar_url)
values (
new.id,
new.email,
new.raw_user_meta_data ->> 'full_name',
new.raw_user_meta_data ->> 'avatar_url'
)
on conflict (id) do update
set email = excluded.email,
display_name = excluded.display_name,
avatar_url = excluded.avatar_url;
return new;
end;
$$;
drop trigger if exists on_auth_user_created on auth.users;
create trigger on_auth_user_created
after insert or update on auth.users
for each row execute function public.handle_new_auth_user();
The trigger fires on update too, so profile fields follow later metadata and email changes. Adapt table and field names to the existing schema. Review every security definer function before shipping it. The profiles table itself needs explicit grants, RLS and policies in the same migration. Take those from the supabase skill.
Verification
- Create, update and delete users and confirm profile lifecycle behavior.
- Replay the trigger path and confirm no duplicate profile.
- Change
raw_user_meta_dataas the user and confirm it changes no authorization outcome. - Test session refresh and expiry in the target runtime with the checks the
supabaseskill defines. - Test the profile table as owner, another user, and anonymous.
- Run the migration from a clean local database and regenerate types.
Claude app, ChatGPT and ZIP download
local coding agent required
This skill requires project files, terminal commands, and network access. Uploading it to a chat app does not provide equivalent execution.
ChatGPT Skills
This workflow needs a local coding environment or capabilities that a chat-only Skills upload does not provide.
Package details
- Package
- auth-implementation/SKILL.md
- Author
- @tushaarmehtaa
- Added
- 7 Mar 2026
- Tags