반응형
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
[Next.js] Next.js 14에서 private route처리하기 (middleware.ts)
리액트에서 private route를 처리할 때 HOC를 사용해오곤 했는데 next에서는 다르게 처리할 것 같아 찾아보니 middleware로 제어하는 방식을 알게되었다. 공식문서의 middleware파트에서도 middleware의 다양
s0ojin.tistory.com
728x90
'코딩 > Next.js' 카테고리의 다른 글
[Next.js] 캐싱 관련 코드 (2) | 2024.09.27 |
---|---|
[next.js] 서버사이트 통신 방식 (0) | 2024.09.20 |
[next.js] 클라이언트 통신방식. (1) | 2024.09.20 |
[React] useActionState 펜딩상태를 체크할 수 있다. (0) | 2024.09.10 |
[next.js] 심심풀이 진행 중... (0) | 2022.09.14 |