ERP-node/frontend/middleware.ts

56 lines
1.7 KiB
TypeScript
Raw Normal View History

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$).*)",
],
};