|
| 1 | +import { NextResponse, type NextRequest } from "next/server"; |
| 2 | +import { getAccessToken } from "./utils/storage"; |
| 3 | + |
| 4 | +export default function middleware(request: NextRequest) { |
| 5 | + const { nextUrl, cookies } = request; |
| 6 | + const accessToken = cookies.get("lettering-access")?.value; |
| 7 | + const { pathname, searchParams } = request.nextUrl; |
| 8 | + |
| 9 | + /* 정적 파일 요청인지 확인 */ |
| 10 | + if ( |
| 11 | + request.nextUrl.pathname.startsWith("/images") || |
| 12 | + request.nextUrl.pathname.endsWith(".svg") || |
| 13 | + request.nextUrl.pathname.endsWith(".png") || |
| 14 | + request.nextUrl.pathname === "/manifest.json" |
| 15 | + ) { |
| 16 | + return NextResponse.next(); |
| 17 | + } |
| 18 | + |
| 19 | + /* /verify/letter 페이지 접근 시 토큰 유무에 따라 처리 */ |
| 20 | + if (pathname === "/verify/letter") { |
| 21 | + const urlParam = searchParams.get("url"); |
| 22 | + |
| 23 | + // 액세스 토큰이 없는 경우 |
| 24 | + if (!accessToken) { |
| 25 | + // `url` 파라미터가 있으면 해당 URL로, 없으면 기본 `/login`으로 이동 |
| 26 | + const redirectUrl = urlParam ? `/login?url=${urlParam}` : "/login"; |
| 27 | + return NextResponse.redirect(new URL(redirectUrl, request.url)); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + if ( |
| 32 | + request.nextUrl.pathname.startsWith("/error") || |
| 33 | + request.nextUrl.pathname.startsWith("/verify") |
| 34 | + ) { |
| 35 | + return NextResponse.next(); |
| 36 | + } |
| 37 | + |
| 38 | + /* 로그인 필요 없는 페이지 */ |
| 39 | + if ( |
| 40 | + request.nextUrl.pathname === "/login" || |
| 41 | + request.nextUrl.pathname.startsWith("/signup") || |
| 42 | + request.nextUrl.pathname.startsWith("/kakao") |
| 43 | + ) { |
| 44 | + // 로그인 되어 있는 경우 메인 페이지로 리다이렉트 |
| 45 | + if (accessToken) { |
| 46 | + const redirectUrl = "/planet"; |
| 47 | + return NextResponse.redirect(new URL(redirectUrl, request.url)); |
| 48 | + } else { |
| 49 | + // 로그인이 필요 없는 페이지는 그냥 다음 요청으로 진행 |
| 50 | + return NextResponse.next(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /* 로그인 필요한 페이지 */ |
| 55 | + if (!accessToken) { |
| 56 | + // 로그인 페이지로 리다이렉트 |
| 57 | + return NextResponse.redirect(new URL("/login", request.url)); |
| 58 | + } |
| 59 | + |
| 60 | + // 로그인 되어 있는 경우 요청 페이지로 진행 |
| 61 | + return NextResponse.next(); |
| 62 | +} |
| 63 | + |
| 64 | +export const config = { |
| 65 | + matcher: [ |
| 66 | + /* |
| 67 | + * Match all request paths except for the ones starting with: |
| 68 | + * - api (API routes) |
| 69 | + * - _next/static (static files) |
| 70 | + * - _next/image (image optimization files) |
| 71 | + * - favicon.ico (favicon file) |
| 72 | + * - robots.txt (robots file) |
| 73 | + */ |
| 74 | + "/((?!api|_next/static|_next/image|favicon.ico|robots.txt|images|manifest.json).*)", |
| 75 | + ], |
| 76 | +}; |
0 commit comments