# NextAuth + Directus Entegrasyonu
NextAuth ile Directus backend'inize bağlanmak için gerekli tüm dosyalar oluşturuldu.
## Kullanım
### 1. Environment Değişkenleri
`.env.local` dosyasında `NEXTAUTH_SECRET` değerini değiştirin:
```bash
# Rastgele bir secret oluşturmak için:
openssl rand -base64 32
```
### 2. Herhangi bir sayfada session kullanımı
```tsx
"use client";
import { useSession, signOut } from "next-auth/react";
export default function Dashboard() {
const { data: session, status } = useSession();
if (status === "loading") {
return
Yükleniyor...
;
}
if (!session) {
return Giriş yapmanız gerekiyor
;
}
return (
Hoşgeldiniz, {session.user?.email}
Access Token: {session.accessToken}
);
}
```
### 3. Server Component'te session kullanımı
```tsx
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export default async function ServerPage() {
const session = await getServerSession(authOptions);
if (!session) {
return Giriş yapmanız gerekiyor
;
}
return Hoşgeldiniz, {session.user?.email}
;
}
```
### 4. API Route'larında kullanım
```tsx
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
export async function GET(request: Request) {
const session = await getServerSession(authOptions);
if (!session) {
return new Response("Unauthorized", { status: 401 });
}
// Directus API'sine istek atarken token kullanın
const response = await fetch(`${process.env.DIRECTUS_URL}/items/your_collection`, {
headers: {
Authorization: `Bearer ${session.accessToken}`,
},
});
const data = await response.json();
return Response.json(data);
}
```
### 5. Middleware ile route koruma
`middleware.ts` dosyası oluşturun:
```tsx
export { default } from "next-auth/middleware";
export const config = {
matcher: ["/dashboard/:path*", "/profile/:path*"],
};
```
## Başlatma
```bash
npm run dev
# veya
yarn dev
```
Tarayıcıda `http://localhost:3000/login` adresine gidin ve giriş yapın.