Autenticação Next.js (Auth.js v5)
Regras
- Centralize a configuração em
auth.ts (exportação NextAuth(): handlers, auth, signIn, signOut). Nunca espalhe segredos de provedores.
- Proteja as rotas em
middleware.ts (wrapper auth seguro para edge) e verifique novamente a sessão dentro de Server Actions/mutações — o middleware é UX, não autorização.
- Leia a sessão em Server Components via
await auth(). Em Client Components use useSession() de next-auth/react com <SessionProvider>.
- Nunca exponha segredos (
AUTH_SECRET, chaves de provedores) com o prefixo NEXT_PUBLIC_. Valide as variáveis de ambiente com Zod na inicialização.
- Verificações de papel/função: estenda o tipo da sessão via augmentação de módulo (
user.role), aplique a verificação no servidor.
Padrões
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [GitHub],
callbacks: {
async session({ session, token }) {
if (session.user) (session.user as { role?: string }).role = token.role as string;
return session;
},
async jwt({ token, user }) {
if (user) token.role = (user as { role?: string }).role ?? 'user';
return token;
},
},
});
export { auth as middleware } from '@/auth';
export const config = { matcher: ['/dashboard/:path*', '/admin/:path*'] };
import { handlers } from '@/auth';
export const { GET, POST } = handlers;
import { auth } from '@/auth';
import { redirect } from 'next/navigation';
export default async function AdminPage() {
const session = await auth();
if (!session?.user) redirect('/login');
if ((session.user as { role?: string }).role !== 'admin')
redirect('/dashboard');
return <AdminView />;
}
import 'next-auth';
declare module 'next-auth' {
interface User { role?: string }
}
Lista de Verificação