Agent skill

Nextjs Authentication

by giuseppe-trisciuoglio in giuseppe-trisciuoglio/developer-kit

Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js).

MITAuto-check: notesBackend & APIs

Install Nextjs Authentication

skills CLI
$ npx skills add giuseppe-trisciuoglio/developer-kit --skill nextjs-authentication -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install giuseppe-trisciuoglio/developer-kit nextjs-authentication --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/giuseppe-trisciuoglio/developer-kit.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/developer-kit-typescript/skills/nextjs-authentication .claude/skills/nextjs-authentication && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
nextjs-authentication
GitHub stars
357
Token cost
~2.8k tokens
SKILL.md length
505 words
Files
7 (incl. references)
Skills in repo
115
Repo updated
First seen
Licence
MIT

At a glance

Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js).

  • Works in 10 steps: Install Dependencies → Configure Environment Variables → Create Auth Configuration → …
  • Setting up authentication flows
  • SKILL.md covers Overview, When to Use, Instructions and Examples, plus 3 more sections
  • Calls npm and openssl; needs AUTH_SECRET and GITHUB_SECRET

What it does

Nextjs Authentication is an agent skill from giuseppe-trisciuoglio/developer-kit. Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js). Use when setting up authentication flows, implementing protected routes, managing sessions in Server Components and Server Actions, configuring OAuth providers, implementing role-based access control, or handling sign-in/sign-out flows in Next.js applications.

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. The skill folder holds 7 other files, including reference files (for example `references/authjs-setup.md`, `references/best-practices.md` and `references/database-adapter.md`).

It sits in Backend & APIs, covering Authorization and RBAC and Authentication. It works with Next.js. The repository describes itself as: Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI. The licence is MIT.

When your agent uses it

  • Setting up authentication flows
  • Implementing protected routes
  • Managing sessions in Server Components and Server Actions
  • Configuring OAuth providers

Example prompts

  • “Use the nextjs-authentication skill to provide authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js)”
  • “/nextjs-authentication”

Requirements

  • Node.js
  • A credential in AUTH_SECRET
  • A credential in GITHUB_SECRET
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Bash

Workflow steps

10 steps, taken from the step headings in SKILL.md.

  1. Install Dependencies
  2. Configure Environment Variables
  3. Create Auth Configuration
  4. Create API Route Handler
  5. Add Middleware for Route Protection
  6. Access Session in Server Components
  7. Secure Server Actions
  8. Handle Sign-In/Sign-Out
  9. Implement Role-Based Access
  10. Extend TypeScript Types

What it can do on your machine

Read from SKILL.md and the folder at commit fe73fb3. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Bash

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • npm
    • openssl

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use npm, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • AUTH_SECRET
    • GITHUB_SECRET
    • GOOGLE_CLIENT_SECRET

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Nextjs Authentication loads about 2.8k tokens when it runs, and up to ~17k if it reads all its reference files. Until then it costs about 97 tokens; SKILL.md has 505 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~97
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~17k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:33
    Create `.env.local` with required variables:
  • NotePre-approves every shell command (allowed-tools: Bash)SKILL.md
    allowed-tools: Read, Write, Edit, Bash

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from giuseppe-trisciuoglio/developer-kit at commit fe73fb3, republished under its MIT licence (© giuseppe-trisciuoglio). 505 words, ~2,811 tokens.

Download SKILL.mdSave it as .claude/skills/nextjs-authentication/SKILL.md (or your agent's skills folder). This skill also uses 6 other files; get the full folder from GitHub.
name
nextjs-authentication
description
Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js). Use when setting up authentication flows, implementing protected routes, managing sessions in Server Components and Server Actions, configuring OAuth providers, implementing role-based access control, or handling sign-in/sign-out flows in Next.js applications.
allowed-tools
Read, Write, Edit, Bash

Next.js Authentication

Overview

Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js), covering the complete authentication lifecycle from initial setup to production-ready role-based access control implementations.

When to Use

  • Setting up Auth.js 5 from scratch or adding OAuth providers
  • Implementing protected routes with Middleware
  • Handling authentication in Server Components and Server Actions
  • Implementing role-based access control (RBAC)
  • Creating credential-based or OAuth sign-in/sign-out flows

Instructions

1. Install Dependencies

Install Auth.js v5 (beta) for Next.js App Router:

bash
npm install next-auth@beta
2. Configure Environment Variables

Create .env.local with required variables:

bash
# Required for Auth.js
AUTH_SECRET="your-secret-key-here"
AUTH_URL="http://localhost:3000"

# OAuth Providers (add as needed)
GITHUB_ID="your-github-client-id"
GITHUB_SECRET="your-github-client-secret"
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

Generate AUTH_SECRET with:

bash
openssl rand -base64 32
3. Create Auth Configuration

Create auth.ts in the project root with providers and callbacks:

typescript
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import Google from "next-auth/providers/google";

export const {
  handlers: { GET, POST },
  auth,
  signIn,
  signOut,
} = NextAuth({
  providers: [
    GitHub({
      clientId: process.env.GITHUB_ID!,
      clientSecret: process.env.GITHUB_SECRET!,
    }),
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
      }
      return token;
    },
    async session({ session, token }) {
      if (token) {
        session.user.id = token.id as string;
      }
      return session;
    },
  },
  pages: {
    signIn: "/login",
    error: "/error",
  },
});
4. Create API Route Handler

Create app/api/auth/[...nextauth]/route.ts:

typescript
export { GET, POST } from "@/auth";
5. Add Middleware for Route Protection

Create middleware.ts in the project root:

typescript
import { auth } from "@/auth";
import { NextResponse } from "next/server";

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const isApiAuthRoute = nextUrl.pathname.startsWith("/api/auth");
  const isPublicRoute = ["/", "/login", "/register"].includes(nextUrl.pathname);
  const isProtectedRoute = nextUrl.pathname.startsWith("/dashboard");

  if (isApiAuthRoute) return NextResponse.next();

  if (!isLoggedIn && isProtectedRoute) {
    return NextResponse.redirect(new URL("/login", nextUrl));
  }

  if (isLoggedIn && nextUrl.pathname === "/login") {
    return NextResponse.redirect(new URL("/dashboard", nextUrl));
  }

  return NextResponse.next();
});

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.png$).*)"],
};
6. Access Session in Server Components

Use the auth() function to access session in Server Components:

tsx
import { auth } from "@/auth";
import { redirect } from "next/navigation";

export default async function DashboardPage() {
  const session = await auth();

  if (!session) {
    redirect("/login");
  }

  return (
    <div>
      <h1>Welcome, {session.user.name}</h1>
    </div>
  );
}
7. Secure Server Actions

Always verify authentication in Server Actions before mutations:

tsx
"use server";

import { auth } from "@/auth";

export async function createTodo(formData: FormData) {
  const session = await auth();

  if (!session?.user) {
    throw new Error("Unauthorized");
  }

  // Proceed with protected action
  const title = formData.get("title") as string;
  await db.todo.create({
    data: { title, userId: session.user.id },
  });
}
8. Handle Sign-In/Sign-Out

Create a login page with server action:

tsx
// app/login/page.tsx
import { signIn } from "@/auth";
import { redirect } from "next/navigation";

export default function LoginPage() {
  async function handleLogin(formData: FormData) {
    "use server";

    const result = await signIn("credentials", {
      email: formData.get("email"),
      password: formData.get("password"),
      redirect: false,
    });

    if (result?.error) {
      return { error: "Invalid credentials" };
    }

    redirect("/dashboard");
  }

  return (
    <form action={handleLogin}>
      <input name="email" type="email" placeholder="Email" required />
      <input name="password" type="password" placeholder="Password" required />
      <button type="submit">Sign In</button>
    </form>
  );
}

For client-side sign-out:

tsx
"use client";

import { signOut } from "next-auth/react";

export function SignOutButton() {
  return <button onClick={() => signOut()}>Sign Out</button>;
}
9. Implement Role-Based Access

Check roles in Server Components:

tsx
import { auth } from "@/auth";
import { unauthorized } from "next/navigation";

export default async function AdminPage() {
  const session = await auth();

  if (session?.user?.role !== "admin") {
    unauthorized();
  }

  return <AdminDashboard />;
}
10. Extend TypeScript Types

Create types/next-auth.d.ts for type-safe sessions:

typescript
import { DefaultSession } from "next-auth";

declare module "next-auth" {
  interface Session {
    user: {
      id: string;
      role: "user" | "admin";
    } & DefaultSession["user"];
  }

  interface User {
    role?: "user" | "admin";
  }
}

declare module "next-auth/jwt" {
  interface JWT {
    id?: string;
    role?: "user" | "admin";
  }
}

Examples

Example 1: Complete Protected Dashboard

Input: User needs a dashboard accessible only to authenticated users

Implementation:

tsx
// app/dashboard/page.tsx
import { auth } from "@/auth";
import { redirect } from "next/navigation";
import { getUserTodos } from "@/app/lib/data";

export default async function DashboardPage() {
  const session = await auth();

  if (!session?.user?.id) {
    redirect("/login");
  }

  const todos = await getUserTodos(session.user.id);

  return (
    <main>
      <h1>Welcome, {session.user.name}</h1>
      <p>Email: {session.user.email}</p>
      <TodoList todos={todos} />
    </main>
  );
}

Output: Dashboard renders only for authenticated users, with their specific data.

Example 2: Role-Based Admin Panel

Input: Admin panel should be accessible only to users with "admin" role

Implementation:

tsx
// app/admin/page.tsx
import { auth } from "@/auth";
import { unauthorized } from "next/navigation";

export default async function AdminPage() {
  const session = await auth();

  if (session?.user?.role !== "admin") {
    unauthorized();
  }

  return (
    <main>
      <h1>Admin Panel</h1>
      <p>Welcome, administrator {session.user.name}</p>
    </main>
  );
}

Output: Only admin users see the panel; others get 401 error.

Example 3: Secure Server Action with Form

Input: Form submission should only work for authenticated users

Implementation:

tsx
// app/components/create-todo-form.tsx
"use server";

import { auth } from "@/auth";
import { revalidatePath } from "next/cache";

export async function createTodo(formData: FormData) {
  const session = await auth();

  if (!session?.user?.id) {
    throw new Error("Unauthorized");
  }

  const title = formData.get("title") as string;

  await db.todo.create({
    data: {
      title,
      userId: session.user.id,
    },
  });

  revalidatePath("/dashboard");
}

// Usage in component
export function CreateTodoForm() {
  return (
    <form action={createTodo}>
      <input name="title" placeholder="New todo..." required />
      <button type="submit">Add Todo</button>
    </form>
  );
}

Output: Todo created only for authenticated user; unauthorized requests throw error.

Show full SKILL.md (237 more words)Show less

Best Practices

  1. Use Server Components by default - Access session directly without client-side JavaScript
  2. Minimize Client Components - Only use useSession() for reactive session updates
  3. Cache session checks - Use React's cache() for repeated lookups in the same render
  4. Middleware for optimistic checks - Redirect quickly, but always re-verify in Server Actions
  5. Treat Server Actions like API endpoints - Always authenticate before mutations
  6. Never hardcode secrets - Use environment variables for all credentials
  7. Implement proper error handling - Return appropriate HTTP status codes
  8. Use TypeScript type extensions - Extend NextAuth types for custom fields
  9. Separate auth logic - Create a DAL (Data Access Layer) for consistent checks
  10. Test authentication flows - Mock auth() function in unit tests

Constraints and Warnings

Critical Limitations
  • Middleware runs on Edge runtime - Cannot use Node.js APIs like database drivers
  • Server Components cannot set cookies - Use Server Actions for cookie operations
  • Session callback timing - Only called on session creation/access, not every request
Common Mistakes
tsx
// ❌ WRONG: Setting cookies in Server Component
export default async function Page() {
  cookies().set("key", "value"); // Won't work
}

// ✅ CORRECT: Use Server Action
async function setCookieAction() {
  "use server";
  cookies().set("key", "value");
}
typescript
// ❌ WRONG: Database queries in Middleware
export default auth(async (req) => {
  const user = await db.user.findUnique(); // Won't work in Edge
});

// ✅ CORRECT: Use only Edge-compatible APIs
export default auth(async (req) => {
  const session = req.auth; // This works
});
Security Considerations
  • Always verify authentication in Server Actions - middleware alone is not enough
  • Use unauthorized() for unauthenticated access, redirect() for other cases
  • Store sensitive tokens in httpOnly cookies
  • Validate all user input before processing
  • Use HTTPS in production
  • Set appropriate cookie sameSite attributes

References

© giuseppe-trisciuoglio, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 6 other files (references) in plugins/developer-kit-typescript/skills/nextjs-authentication of giuseppe-trisciuoglio/developer-kit.

  • SKILL.md
  • references/authjs-setup.md
  • references/best-practices.md
  • references/database-adapter.md
  • references/examples.md
  • references/oauth-providers.md
  • references/testing-patterns.md

Open the folder on GitHubat commit fe73fb3

Compare with similar skills

Nextjs Authentication next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Nextjs Authentication compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Nextjs Authentication this skillgiuseppe-trisciuoglio/developer-kit357—~2.8kAutomated safety check: NotesMIT
Memstack Security API Auditcwinvestments/memstack423—~3.9kAutomated safety check: PassProprietary
Authaiskillstore/marketplace433—~1.6kAutomated safety check: PassNone
Supabase Development and Debuggingsupabase/agent-skills2.7k3 repos~3.6kAutomated safety check: PassMIT
Payloadpayloadcms/payload45k5 repos~6.2kAutomated safety check: PassMIT
Supabasecurvenote/curvenote1705 repos~2.2kAutomated safety check: PassCustom licence

Similar skills

  • Memstack Security API Audit

    cwinvestments/memstack

    A skill your agent uses when the user says 'audit API', 'check API security', 'API routes security', 'endpoint audit', 'check my routes', or needs to verify API route protection.

    423 GitHub stars~3.9k tokensUpdated 14 days ago
    Backend & APIsAuto-check passed
  • Auth

    aiskillstore/marketplace

    Authentication and access control skill for Next.js 15 + Supabase applications.

    433 GitHub stars~1.6k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Official

    General Supabase skill for database, auth, Edge Functions, Realtime and storage work, plus client libraries, migrations, security audits, debugging and reading logs.

    2.7k GitHub starsUsed in 3 repos~3.6k tokens
    Backend & APIsAuto-check passed
  • Payload

    payloadcms/payload

    A skill your agent uses when working with Payload projects (payload.config.ts, collections, fields, hooks, access control, Payload API).

    45k GitHub starsUsed in 5 repos~6.2k tokens
    Backend & APIsAuto-check passed
  • Supabase

    curvenote/curvenote

    A skill your agent uses when doing ANY task involving Supabase.

    170 GitHub starsUsed in 5 repos~2.2k tokens
    Backend & APIsAuto-check passed
  • Cognito

    itsmostafa/aws-agent-skills

    AWS Cognito user authentication and authorization service. An agent skill from itsmostafa/aws-agent-skills.

    1.2k GitHub starsUsed in 1 repo~2.3k tokens
    Backend & APIsAuto-check passed

More from giuseppe-trisciuoglio/developer-kit

All 115 skills in this repo
  • Nestjs Drizzle Crud Generator

    giuseppe-trisciuoglio/developer-kit

    Generates complete CRUD modules for NestJS applications with Drizzle ORM.

    357 GitHub stars~1.3k tokensUpdated 1 mo ago
    Auto-check: notes
  • Spring Boot Actuator

    giuseppe-trisciuoglio/developer-kit

    Provides patterns to configure Spring Boot Actuator for production-grade monitoring, health probes, secured management endpoints, and Micrometer metrics across JVM services.

    357 GitHub stars~2.2k tokensUpdated 1 mo ago
    Auto-check: notes
  • Spring Boot Crud Patterns

    giuseppe-trisciuoglio/developer-kit

    Provides and generates complete CRUD workflows for Spring Boot 3 services.

    357 GitHub stars~2.5k tokensUpdated 1 mo ago
    Auto-check: notes
  • Spring Boot Security JWT

    giuseppe-trisciuoglio/developer-kit

    Provides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based…

    357 GitHub stars~3.9k tokensUpdated 1 mo ago
    Auto-check: notes
  • AWS CLI Beast

    giuseppe-trisciuoglio/developer-kit

    Provides advanced AWS CLI patterns for managing EC2, Lambda, S3, DynamoDB, RDS, VPC, IAM, and CloudWatch.

    357 GitHub stars~1.7k tokensUpdated 1 mo ago
    Auto-check: notes
  • PR Review Comments

    giuseppe-trisciuoglio/developer-kit

    Posts review findings from a JSON file as inline comments on a GitHub Pull Request, attaching each comment to its file and line.

    357 GitHub stars~1k tokensUpdated 1 mo ago
    Auto-check: notes

Works with

Categories

Questions about Nextjs Authentication

What does Nextjs Authentication do?

Provides authentication implementation patterns for Next.js 15+ App Router using Auth.js 5 (NextAuth.js). Nextjs Authentication is an agent skill from giuseppe-trisciuoglio/developer-kit.js).

When should I use Nextjs Authentication?

Nextjs Authentication fits situations like: setting up authentication flows; implementing protected routes; managing sessions in Server Components and Server Actions; configuring OAuth providers.

How do I install Nextjs Authentication in Claude Code?

Run `npx skills add giuseppe-trisciuoglio/developer-kit --skill nextjs-authentication -a claude-code`. Or copy the skill folder (plugins/developer-kit-typescript/skills/nextjs-authentication in giuseppe-trisciuoglio/developer-kit) into .claude/skills/nextjs-authentication in your project. Claude Code loads it when a task matches its description.

How do I install Nextjs Authentication in Codex?

Run `npx skills add giuseppe-trisciuoglio/developer-kit --skill nextjs-authentication -a codex`. Or copy the skill folder (plugins/developer-kit-typescript/skills/nextjs-authentication in giuseppe-trisciuoglio/developer-kit) into .agents/skills/nextjs-authentication in your project. Codex loads it when a task matches its description.

Can I use Nextjs Authentication in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add giuseppe-trisciuoglio/developer-kit --skill nextjs-authentication -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/nextjs-authentication, .gemini/skills/nextjs-authentication, .github/skills/nextjs-authentication and .opencode/skills/nextjs-authentication in your project.

What does Nextjs Authentication need to run?

Going by SKILL.md and its folder, Nextjs Authentication needs the command-line tools its instructions call (npm and openssl) and credentials named AUTH_SECRET, GITHUB_SECRET and GOOGLE_CLIENT_SECRET. Our summary lists: Node.js; A credential in AUTH_SECRET; A credential in GITHUB_SECRET. Its frontmatter pre-approves these tools: Read, Write, Edit, Bash.

Does Nextjs Authentication access the network?

SKILL.md contains no URLs. Its commands use npm, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Nextjs Authentication safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file; pre-approves every shell command (allowed-tools: bash)), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Nextjs Authentication use?

Nextjs Authentication is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Nextjs Authentication use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 14k tokens, read only when the agent opens those files.

What are the alternatives to Nextjs Authentication?

Skills that share tags, products or a category with Nextjs Authentication: Memstack Security API Audit (cwinvestments/memstack, 423 stars), Auth (aiskillstore/marketplace, 433 stars), Supabase Development and Debugging (supabase/agent-skills, 2.7k stars) and Payload (payloadcms/payload, 45k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Nextjs Authentication?

giuseppe-trisciuoglio (a GitHub user) maintains it in giuseppe-trisciuoglio/developer-kit, which has 357 GitHub stars. The repository holds 115 skills in this directory. The repository was last updated on September 10, 2026.

Source: giuseppe-trisciuoglio/developer-kit on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.