The Complete Production SOP: How to Deploy and Run Auth.js (NextAuth v5) Edge-Compatible Authentication in Autonomous AI Agents
Production SOP to install and run NextAuth v5 (Auth.js) edge auth in Codex, Claude Code, & Cursor. Includes verified prompts, edge middleware, and adapters.
Technical Overview & Architectural Context
Autonomous coding agents like Codex, Claude Code, Cursor, and Windsurf frequently introduce breaking regressions when scaffolding authentication in Next.js 14 and 15. The most pervasive failure occurs when agents mix deprecated NextAuth v4 API patterns (such as importing from 'next-auth/next' or reading req.headers in server route handlers) with modern NextAuth v5/Auth.js architecture. Furthermore, agents routinely attempt to bind database ORMs like Prisma directly into Edge runtime middleware (`middleware.ts`), triggering fatal Node.js runtime compatibility crashes at build or request time. Enforcing the `next-auth-v5-authjs-providers` deterministic skill completely eliminates this hallucination profile. It guides agents through the architectural split required by Auth.js: splitting edge-compatible auth configuration (`auth.config.ts`) from Node-runtime adapter initialization (`auth.ts`). By establishing rigid operational boundaries around session callbacks, route handlers, and environment secret injection, this skill guarantees reliable, edge-compatible authentication workflows across any autonomous agent session.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Mount the Auth.js v5 skill manifest into your agent's configuration directory to register execution triggers.
Autonomous runtimes discover capabilities via the universal `SKILL.md` format. When mounted in `.agents/skills` or `.claude/skills`, agents parse the frontmatter triggers (`setup next-auth v5 auth.ts`, `authjs edge middleware`, `custom session callback nextauth`) and inject the exact operational SOP into system context upon user match.
mkdir -p .agents/skills/next-auth-v5-authjs-providers && curl -fsSL https://askills.dev/api/skills/next-auth-v5-authjs-providers/raw -o .agents/skills/next-auth-v5-authjs-providers/SKILL.md---
name: "next-auth-v5-authjs-providers"
description: "Authenticate users via OAuth, magic email links, and credentials with NextAuth v5 / Auth.js."
metadata:
author: "Auth.js"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "setup next-auth v5 auth.ts"
- "authjs edge middleware"
- "custom session callback nextauth"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Auth.js (NextAuth v5) Edge-Compatible Authentication
Configures Auth.js / NextAuth v5: auth.ts configuration, OAuth providers (Google, GitHub, Discord), database adapters (@auth/prisma-adapter), Edge middleware protection with auth(), and session callbacks.
## When to Invoke
Invoke this skill whenever you need to:
- setup next-auth v5 auth.ts
- authjs edge middleware
- custom session callback nextauth
## Execution SOP & Rules
1. Split Edge config: define `auth.config.ts` containing providers and edge-compatible callbacks.
2. Create main `auth.ts`: import `auth.config.ts`, attach Prisma/Drizzle adapter, and export `{ handlers, signIn, signOut, auth }`.
3. Create App Router route handler: `app/api/auth/[...nextauth]/route.ts` exporting `export const { GET, POST } = handlers`.
4. Configure Edge Middleware in `middleware.ts` importing `auth` from `auth.config.ts` (never import adapter or Node DB clients here).
5. Type augment `next-auth` module for `Session` and `JWT` to retain custom user attributes.Place the SKILL.md in the project root under `.cursor/rules` or `.claude/skills` to preserve LLM context tokens by restricting the prompt to domain-specific instructions without generic scaffolding bloat.
Do not grant shell execution permissions (`shell_exec: true`) to the skill. NextAuth setup only requires workspace file creation and edits; restricting permissions prevents the agent from attempting unsolicited remote installs.
Environment Secrets & Dependency Validation
Declare dependencies and configure local environment secrets using secret managers or non-committed templates.
NextAuth v5 requires `AUTH_SECRET` (formerly `NEXTAUTH_SECRET`) and provider credentials (e.g., `AUTH_GITHUB_ID`, `AUTH_GITHUB_SECRET`). Provide these variables via `.env.local` and install the v5 release tag (`beta`) to prevent the agent from inadvertently pulling v4 dependencies.
pnpm add next-auth@beta @auth/core @auth/prisma-adapter && npx auth secretRun `npx auth secret` directly to automatically generate and write `AUTH_SECRET` into `.env.local`, avoiding the hazard of manual key exposure inside agent interaction logs.
Never allow the agent to commit `.env.local`. Always confirm that `.env*.local` is present in `.gitignore` before allowing file write actions.
Intent Matching & Trigger Invocation
Prompt the agent using explicit trigger phrases to activate the deterministic split-architecture pattern.
Invoke the skill using the exact trigger phrases defined in the SKILL.md metadata. When matching triggers like `setup next-auth v5 auth.ts` and `authjs edge middleware`, the agent generates the decoupled Edge and Node configuration files.
Structure prompts to request both `auth.config.ts` and `auth.ts` explicitly to prevent LLMs from consolidating database drivers into the middleware path.
Verification, Linting & Output Quality Gate
Execute Next.js type checking and dynamic route analysis to verify Edge compatibility.
The skill enforces a completion checklist requiring local type-checking and build validation. Running Next.js build validates that `middleware.ts` imports no Node-only modules (such as `net`, `tls`, or binary database clients).
pnpm tsc --noEmit && pnpm next buildUse `git diff --stat` to review all generated authentication files and verify that module augmentations correctly expose custom session fields.
Real-World Scenario: Configure NextAuth v5 with GitHub OAuth, Edge Middleware, and Custom User ID Session
“setup next-auth v5 auth.ts with GitHub provider and edge middleware. Ensure the session callback attaches user.id to the session and types are properly augmented.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent imported `auth.ts` (which references Prisma, Node ORMs, or Node-native modules) directly inside `middleware.ts`. Edge Middleware cannot bundle Node standard libraries.
// middleware.ts
import NextAuth from 'next-auth';
import authConfig from './auth.config'; // Import the Edge-safe config ONLY
export const { auth: middleware } = NextAuth(authConfig);
export const config = { matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'] };Root Cause: Default NextAuth v5 session type definitions lack custom attributes in the session callback without explicit TypeScript declaration merging.
// types/next-auth.d.ts
import { type DefaultSession } from 'next-auth';
declare module 'next-auth' {
interface Session {
user: {
id: string;
} & DefaultSession['user'];
}
}Frequently Asked Questions (Auth.js (NextAuth v5) Edge-Compatible Authentication SOP)
Q:Can I use Auth.js (NextAuth v5) Edge-Compatible Authentication across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres strictly to the universal SKILL.md specification. Runtimes such as Codex Desktop, Claude Code CLI, Cursor, and Windsurf parse the triggers and boundary rules consistently across projects.
Q:How does Auth.js (NextAuth v5) Edge-Compatible Authentication prevent context window overflow during long agent sessions?
Instead of inserting exhaustive auth documentation into system prompts, the skill activates only when explicit triggers match. Its compact SOP focuses on architecture constraints (edge decoupling, typing, route handlers), saving thousands of context tokens.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires only standard workspace file read and write permissions to construct configuration files, without needing shell escalation or external network access.
Ready to equip your autonomous agent with Auth.js (NextAuth v5) Edge-Compatible Authentication?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.