Files
next-dj/README-AUTH.md
Beyhan Oğur e881f38e4e first commit
2026-04-26 22:12:36 +03:00

107 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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 <div>Yükleniyor...</div>;
}
if (!session) {
return <div>Giriş yapmanız gerekiyor</div>;
}
return (
<div>
<h1>Hoşgeldiniz, {session.user?.email}</h1>
<p>Access Token: {session.accessToken}</p>
<button onClick={() => signOut()}>Çıkış Yap</button>
</div>
);
}
```
### 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 <div>Giriş yapmanız gerekiyor</div>;
}
return <div>Hoşgeldiniz, {session.user?.email}</div>;
}
```
### 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.