✍ 따뜻한 개발 공부
next.js의 미들웨어 / 삭제된 페이지인경우 페이지 띄워주기
따따시
2023. 3. 2. 23:28
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { doc, getDoc } from "firebase/firestore";
import { dbService } from "./config/firebase";
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
console.log("request.nextUrl.pathname:", request.nextUrl.pathname);
const nextURL = request.nextUrl.pathname;
const splitURL = nextURL.split("/");
const id = splitURL[2];
console.log("id : ", id);
const snap = await getDoc(doc(dbService, "recipe", id));
if (snap.exists()) {
return;
} else {
return NextResponse.redirect(new URL("/deletePage", request.url));
}
}
// See "Matching Paths" below to learn more
export const config = {
matcher: "/detailRecipePage/:path*",
};
config의 matcher에서 /detailRecipePage/:path*의 저 Path 부분에 포스트 id값들이 들어가고
만약 파베에 id가 없을 경우 snap.exit()가 없을거고
그럼 else문이 실행되면서 redirect로 삭제페이지로 갈 수 있도록 미들웨어를 사용해주면 되는 것!!!!!
아 그리고 middleware.ts 파일은 root 폴더에다가 만들어주면 된다.