
✅ Middleware, Matcher 사용 예시
(/middleware.ts)
import { NextRequest, NextResponse } from "next/server";
import getSession from "./lib/session";
interface Routes {
[key: string]: boolean;
}
const publicOnlyUrls: Routes = {
"/": true,
"/login": true,
"/sms": true,
"/create-account": true,
"/github/start": true,
"/github/complete": true,
};
export async function middleware(request: NextRequest) {
const session = await getSession();
const exists = publicOnlyUrls[request.nextUrl.pathname];
if (!session.id) {
if (!exists) {
return NextResponse.redirect(new URL("/", request.url));
}
} else {
if (exists) {
return NextResponse.redirect(new URL("/home", request.url));
}
}
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
/* const publicUrls = new Set(["/", "/login", "/sms", "/create-account"]);
export async function middleware(request: NextRequest) {
const isPublicPath = publicUrls.has(request.nextUrl.pathname);
const isLoggedIn = Boolean((await getSession()).id);
if (!isLoggedIn && !isPublicPath) {
return NextResponse.redirect(new URL("/", request.url));
}
if (isLoggedIn && isPublicPath) {
return NextResponse.redirect(new URL("/home", request.url));
}
} */
matcher 안에는 source와 missing이라는 속성이 들어갈 수 있다.
(객체 안에 source와 missing을 담아 matcher 안에 담을 수 있다.)
missing: [{type: "header", key: "next-router-prefetch"}]
-> header가 없을 때 middleware를 실행함
'♣️ Next.js 14' 카테고리의 다른 글
| Next.js 14 - 원 단위로 바꾸기, 날짜 포맷하기 (0) | 2025.12.03 |
|---|---|
| Next.js 14 - Image component (0) | 2025.12.03 |
| Next.js 14 - useFormState(useActionState) (0) | 2025.09.17 |
| Next.js 14 - useFormStatus (0) | 2025.09.17 |
| Next.js 14 - Server Action (0) | 2025.09.17 |