import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; /** * Next.js 미들웨어 * 페이지 렌더링 전에 실행되어 인증 상태를 확인하고 리다이렉트 처리 */ export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // 인증 토큰 확인 const token = request.cookies.get("authToken")?.value || request.headers.get("authorization")?.replace("Bearer ", ""); // /login 페이지 접근 시 if (pathname === "/login") { // 토큰이 있으면 메인 페이지로 리다이렉트 if (token) { const url = request.nextUrl.clone(); url.pathname = "/main"; return NextResponse.redirect(url); } // 토큰이 없으면 로그인 페이지 표시 return NextResponse.next(); } // 인증이 필요한 페이지들 const protectedPaths = ["/main", "/admin", "/dashboard", "/settings"]; const isProtectedPath = protectedPaths.some((path) => pathname.startsWith(path)); if (isProtectedPath && !token) { // 인증되지 않은 사용자는 로그인 페이지로 리다이렉트 const url = request.nextUrl.clone(); url.pathname = "/login"; return NextResponse.redirect(url); } return NextResponse.next(); } /** * 미들웨어가 실행될 경로 설정 */ export const config = { matcher: [ /* * 다음 경로를 제외한 모든 요청에 대해 실행: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) * - public 폴더의 파일들 */ "/((?!api|_next/static|_next/image|favicon.ico|.*\\.png$|.*\\.jpg$|.*\\.jpeg$|.*\\.svg$).*)", ], };