authjs
БесплатноБез исполняемых скриптовНе проверенAuth.js (formerly NextAuth.js) is an open-source authentication library that adds OAuth sign-in, magic links, credentials and WebAuthn to Next.js, SvelteKit…
Об этом скилле
Auth.js (NextAuth) — Authentication for the Web
Overview
Auth.js is the successor to NextAuth.js. For Next.js you install next-auth@beta (the v5 line; latest on npm is still v4.24). Config lives in one root auth.ts that exports handlers, auth, signIn and signOut; auth() replaces getServerSession, getToken and withAuth everywhere (server components, route handlers, proxy). Environment variables use the AUTH_ prefix and provider credentials named AUTH_<PROVIDER>_ID / AUTH_<PROVIDER>_SECRET are picked up automatically.
Status to know before choosing it: since September 2025 the project is maintained by the Better Auth team, in maintenance mode (security fixes, no new features), and Better Auth recommends itself for new projects. Existing Auth.js apps keep working; for a greenfield app, mention Better Auth as the alternative and let the user decide.
Instructions
- Install and create the secret:
npm install next-auth@beta
npx auth secret # writes AUTH_SECRET to .env.local
- Create
auth.tsat the project root:
import NextAuth from "next-auth";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [Google, GitHub], // reads AUTH_GOOGLE_ID/SECRET and AUTH_GITHUB_ID/SECRET
pages: { signIn: "/login" },
});
- Add the route handler
app/api/auth/[...nextauth]/route.ts:
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
Register each provider's callback URL as
https://your-domain/api/auth/callback/<provider>(for local developmenthttp://localhost:3000/api/auth/callback/github). Behind a proxy or on a non-Vercel host setAUTH_URLorAUTH_TRUST_HOST=true.Protect routes. On Next.js 16 the file is
proxy.ts; on earlier versions it ismiddleware.tswithexport { auth as middleware }:
// proxy.ts
export { auth as proxy } from "@/auth";
export const config = { matcher: ["/dashboard/:path*", "/admin/:path*"] };
For per-route logic pass a function and use the authorized callback (below). Do not rely on proxy alone: also call auth() inside pages, route handlers and server actions that return private data.
Read the session:
const session = await auth()on the server;useSession()fromnext-auth/reactin client components (wrap them in<SessionProvider>). Sign in and out with server actions:await signIn("github"),await signOut().Add a database adapter when you need stored users, accounts, verification tokens or magic links. Adapters are scoped packages (
@auth/drizzle-adapter,@auth/prisma-adapter, ...); passadapter: DrizzleAdapter(db). With an adapter the default session strategy becomesdatabase; the Credentials provider only works withsession: { strategy: "jwt" }.Roles and custom fields: copy them into the token in
jwt, then into the session insession, and extend the types.
callbacks: {
jwt({ token, user }) {
if (user) token.role = user.role; // user exists only at sign-in
return token;
},
session({ session, token }) {
session.user.id = token.sub!;
session.user.role = token.role as string;
return session;
},
authorized({ auth, request }) { // used by the proxy/middleware wrapper
if (request.nextUrl.pathname.startsWith("/admin")) return auth?.user?.role === "admin";
return true;
},
},
// types/next-auth.d.ts
import "next-auth";
declare module "next-auth" {
interface User { role?: string }
interface Session { user: { id: string; role?: string } & DefaultSession["user"] }
}
declare module "next-auth/jwt" { interface JWT { role?: string } }
A role stored in the JWT changes only when the user signs in again.
- Edge runtimes cannot open database TCP connections. If the proxy runs on the edge, split the config:
auth.config.tsholds providers and callbacks without the adapter,auth.tsspreads it and adds the adapter andsession: { strategy: "jwt" }, andproxy.tsbuildsNextAuth(authConfig).auth. The edge instance can check the session cookie but cannot read the database.
Examples
Example 1: Add GitHub login to a Next.js 15 app
User request: "Add Sign in with GitHub to my Next.js app and show the user's avatar in the header."
Run npm install next-auth@beta && npx auth secret, create a GitHub OAuth app with callback http://localhost:3000/api/auth/callback/github, put AUTH_GITHUB_ID and AUTH_GITHUB_SECRET in .env.local, then add auth.ts and the route handler from the steps above. In the header:
import { auth, signIn, signOut } from "@/auth";
export default async function UserNav() {
const session = await auth();
if (!session?.user) {
return <form action={async () => { "use server"; await signIn("github"); }}><button>Sign in with GitHub
Установить authjs в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл authjs?
Auth.js (formerly NextAuth.js) is an open-source authentication library that adds OAuth sign-in, magic links, credentials and WebAuthn to Next.js, SvelteKit, Express and other frameworks. Use when a user asks to add login with Google or GitHub, set up NextAuth v5, protect routes with middleware or proxy, add roles to the session, or connect a database adapter such as Drizzle or Prisma. Notes that the project is in maintenance mode under Better Auth.
Как установить скилл authjs?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл authjs запускает скрипты?
Нет, скилл состоит только из инструкций (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