Używamy cookies, żeby zwiększyć Twoje doświadczenia na stronie
CodeWorlds

Authentication - NextAuth.js

System logowania użytkowników.

NextAuth Setup 🔐

1npm install next-auth
1// app/api/auth/[...nextauth]/route.ts
2import NextAuth from 'next-auth';
3import GoogleProvider from 'next-auth/providers/google';
4
5const handler = NextAuth({
6  providers: [
7    GoogleProvider({
8      clientId: process.env.GOOGLE_CLIENT_ID!,
9      clientSecret: process.env.GOOGLE_CLIENT_SECRET!
10    })
11  ]
12});
13
14export { handler as GET, handler as POST };

Protected Routes 🛡️

1import { getServerSession } from 'next-auth';
2
3export default async function Dashboard() {
4  const session = await getServerSession();
5  
6  if (!session) {
7    redirect('/api/auth/signin');
8  }
9
10  return <div>Welcome {session.user.name}!</div>;
11}

Do zobaczenia! 🚀

Przejdź do CodeWorlds