Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

nextauth

БесплатноБез исполняемых скриптовНе проверен

NextAuth.js authentication for Next.js. Covers providers, sessions, and callbacks. Use for Next.js authentication. USE WHEN: user mentions "NextAuth"…

claude-dev-suiteот claude-dev-suite★ 51 звезда на GitHub

Об этом скилле

NextAuth.js Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: nextauth for comprehensive documentation.

Basic Setup (App Router)

// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import { authOptions } from '@/lib/auth';

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
// lib/auth.ts
import { NextAuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from './prisma';

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        const user = await prisma.user.findUnique({
          where: { email: credentials?.email },
        });
        if (user && await verifyPassword(credentials?.password, user.password)) {
          return user;
        }
        return null;
      },
    }),
  ],
  callbacks: {
    async session({ session, user }) {
      session.user.id = user.id;
      return session;
    },
  },
  pages: {
    signIn: '/login',
    error: '/auth/error',
  },
};

Client Usage

'use client';
import { useSession, signIn, signOut } from 'next-auth/react';

function AuthButton() {
  const { data: session, status } = useSession();

  if (status === 'loading') return <Spinner />;

  if (session) {
    return (
      <div>
        <span>{session.user?.email}</span>
        <button onClick={() => signOut()}>Sign out</button>
      </div>
    );
  }

  return <button onClick={() => signIn('google')}>Sign in</button>;
}

Server-Side Auth

// In Server Component
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

async function ProtectedPage() {
  const session = await getServerSession(authOptions);

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

  return <div>Welcome {session.user.name}</div>;
}

When NOT to Use This Skill

  • Generic OAuth 2.0 flows - Use oauth2 skill for platform-agnostic OAuth
  • Custom JWT implementation - Use jwt skill for custom token logic
  • Non-Next.js frameworks - Use framework-specific auth (Express Passport, etc.)
  • Remix/SvelteKit - Use their native auth solutions

Type Extensions

// types/next-auth.d.ts
declare module 'next-auth' {
  interface Session {
    user: { id: string; role: string } & DefaultSession['user'];
  }
}

Anti-Patterns

Anti-Pattern Why It's Bad Correct Approach
No NEXTAUTH_SECRET Security vulnerability Always set in production
Client-side session checks only Can be bypassed Use getServerSession()
Hardcoded provider credentials Security risk Use environment variables
No error handling Poor UX Implement custom error pages
Mixing session strategies Inconsistent behavior Stick to JWT or database
No CSRF protection Vulnerable to attacks Use default CSRF (enabled by default)

Quick Troubleshooting

Issue Cause Solution
"Configuration error" Missing required env vars Check NEXTAUTH_URL and NEXTAUTH_SECRET
Session is null Not authenticated or session expired Check signIn() was called
"Callback URL error" Invalid redirect Whitelist URLs in provider settings
Type errors Missing type extensions Create types/next-auth.d.ts
Session not updating Cache issue Call update() from useSession
CORS errors Wrong domain Ensure NEXTAUTH_URL matches deployment URL

Production Readiness

Security Configuration

// lib/auth.ts
import { NextAuthOptions } from 'next-auth';

export const authOptions: NextAuthOptions = {
  // Secure session configuration
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },

  // Secure cookies
  cookies: {
    sessionToken: {
      name: process.env.NODE_ENV === 'production'
        ? '__Secure-next-auth.session-token'
        : 'next-auth.session-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV === 'production',
      },
    },
  },

  // Callbacks for security
  callbacks: {
    async jwt({ token, user, account }) {
      if (user) {
        token.id = user.id;
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      session.user.id = token.id as string;
Полный SKILL.md на GitHub

Установить nextauth в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob
Write
Edit

Вложенные файлы

quick-ref/callbacks.mdquick-ref/setup.md

FAQ

Что делает скилл nextauth?

NextAuth.js authentication for Next.js. Covers providers, sessions, and callbacks. Use for Next.js authentication. USE WHEN: user mentions "NextAuth", "Next.js auth", "Auth.js", asks about "Next.js authentication", "App Router auth", "next-auth", "authentication providers" DO NOT USE FOR: generic OAuth (use oauth2 skill), JWT implementation (use jwt skill), non-Next.js projects, Express/Fastify auth

Как установить скилл nextauth?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл nextauth запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить nextauth с