import { NextResponse, NextRequest } from "next/server"; const protectedApi = [ /^\/api\/posts\/[^/]+\/pin$/, /^\/api\/posts\/[^/]+\/approve$/, ]; export async function middleware(req: NextRequest) { const { pathname } = req.nextUrl; const response = NextResponse.next(); // 쿠키에 uid가 없으면 어드민으로 자동 로그인 (기본값) const uid = req.cookies.get("uid")?.value; if (!uid) { // 어드민 사용자 ID 가져오기 (DB 조회 대신 하드코딩 - 실제 환경에서는 다른 방식 사용 권장) // 어드민 nickname은 "admin"으로 고정되어 있다고 가정 // 실제 userId는 DB에서 가져와야 하지만, middleware는 비동기 DB 호출을 제한적으로 지원 // 대신 page.tsx에서 처리하도록 함 // 페이지 요청일 경우만 쿠키 설정 시도 // API는 제외하고 페이지만 처리 if (!pathname.startsWith("/api")) { // 페이지 레벨에서 처리하도록 함 (쿠키는 클라이언트 측에서 설정 필요) } } const needAuth = protectedApi.some((re) => re.test(pathname)); if (needAuth && !uid) { return new NextResponse(JSON.stringify({ error: "Unauthorized" }), { status: 401 }); } return response; } export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"], };