코딩/Next.js

[Nextjs] 프로텍트 라우팅(로그인 여부 확인 후 라우팅 처리)

카슈밀 2025. 3. 2. 01:28
반응형
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export async function middleware(req: NextRequest) {
    const cookieData = await cookies();
    const token = cookieData.get("TokenData");
    const publicPaths = ["/login", "/sign-up"];
    const isPublicPath = publicPaths.includes(req.nextUrl.pathname);
    const isFile = req.nextUrl.pathname.match(/\.(.*)$/);
    const isApiRoute = req.nextUrl.pathname.startsWith("/api");

    if (isFile || isApiRoute) {
        return NextResponse.next();
    }

    if (isPublicPath && token) {
        return NextResponse.redirect(new URL("/home", req.url));
    }

    if (!isPublicPath && !token) {
        return NextResponse.redirect(new URL("/login", req.url));
    }

    return NextResponse.next();
}

 

왜 안되지 하고 있는데, 위치를 잘못 넣었다.

src/app/middleware.tsx

가 아닌

src/middleware.tsx로 해야하는 것...

 

 

== 참고 문서 ===

https://nextjs.org/docs/app/building-your-application/routing/middleware

 

Routing: Middleware | Next.js

Learn how to use Middleware to run code before a request is completed.

nextjs.org

https://s0ojin.tistory.com/76

 

[Next.js] Next.js 14에서 private route처리하기 (middleware.ts)

리액트에서 private route를 처리할 때 HOC를 사용해오곤 했는데 next에서는 다르게 처리할 것 같아 찾아보니 middleware로 제어하는 방식을 알게되었다. 공식문서의 middleware파트에서도 middleware의 다양

s0ojin.tistory.com

 

728x90