Kimlik doğrulama token'ı kontrolü yaparak route'ları koruyan middleware.
import { NextRequest, NextResponse } from class=class="text-emerald-400">"text-emerald-400">'next/server'
const protectedPaths = [class=class="text-emerald-400">"text-emerald-400">'/dashboard', class=class="text-emerald-400">"text-emerald-400">'/settings', class=class="text-emerald-400">"text-emerald-400">'/profile']
const authPages = [class=class="text-emerald-400">"text-emerald-400">'/login', class=class="text-emerald-400">"text-emerald-400">'/register']
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const token = request.cookies.get(class=class="text-emerald-400">"text-emerald-400">'auth-token')?.value
const isProtected = protectedPaths.some(path => pathname.startsWith(path))
const isAuthPage = authPages.some(path => pathname.startsWith(path))
if (isProtected && !token) {
const loginUrl = new URL(class=class="text-emerald-400">"text-emerald-400">'/login', request.url)
loginUrl.searchParams.set(class=class="text-emerald-400">"text-emerald-400">'redirect', pathname)
return NextResponse.redirect(loginUrl)
}
if (isAuthPage && token) {
return NextResponse.redirect(new URL(class=class="text-emerald-400">"text-emerald-400">'/dashboard', request.url))
}
return NextResponse.next()
}
export const config = {
matcher: [class=class="text-emerald-400">"text-emerald-400">'/dashboard/:path*', class=class="text-emerald-400">"text-emerald-400">'/settings/:path*', class=class="text-emerald-400">"text-emerald-400">'/profile/:path*', class=class="text-emerald-400">"text-emerald-400">'/login', class=class="text-emerald-400">"text-emerald-400">'/register'],
}Proje kök dizinine middleware.ts olarak kaydedin. Kimlik doğrulaması olmayan kullanıcıları /login'e yönlendirir ve giriş yapmış kullanıcıları kimlik doğrulama sayfalarından uzaklaştırır. protectedPaths'i uygulamanıza göre özelleştirin.
Fikrinizi nasıl hayata geçirebileceğimizi konuşalım. İlk konseptten üretime hazır ürüne kadar — yanınızdayız.