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★ 51 звезда на GitHubОб этом скилле
NextAuth.js Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:nextauthfor 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
oauth2skill for platform-agnostic OAuth - Custom JWT implementation - Use
jwtskill 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;
Установить nextauth в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
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), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic