개발자 박가나
[250108 TIL] 본캠프 69일차 (MiddleWare) 본문
요청이 완료되기 전에 특정 동작을 실행시킬 수 있는 기능을 제공한다.
/* src/middleware.ts */
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url));
}
export const config = {
matcher: '/about/:path*',
};
MiddleWare는 Next.js가 처리하는 모든 route를 대상으로 동작하지만, 특정 path에서만 동작하게 하고 싶다면 matcher를 사용할 수 있다.
export const config = {
matcher: '/about/:path*',
};
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
};
matcher는 빌드 타임에 생성되어 Next.js 서버에 적용되기 때문에 동적인 값은 사용할 수 없지만, 동적인 값으로 matcher를 작동시키고 싶거나 path가 동일하더라도 특정 조건에서만 MiddleWare를 작동시키고 싶은 경우에는 조건문을 사용할 수 있다.
/* src/middleware.ts */
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/about')) {
return NextResponse.rewrite(new URL('/about-2', request.url));
}
if (request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.rewrite(new URL('/dashboard/user', request.url));
}
}
'내일배움캠프' 카테고리의 다른 글
[250113 TIL] 본캠프 72일차 (면접카타) (0) | 2025.01.13 |
---|---|
[250110 TIL] 본캠프 71일차 (모의면접) (0) | 2025.01.10 |
[250107 TIL] 본캠프 68일차 (React Hook Form과 Zod) (0) | 2025.01.07 |
[250106 TIL] 본캠프 67일차 (면접카타) (0) | 2025.01.06 |
[250103 TIL] 본캠프 66일차 (크롤링) (0) | 2025.01.03 |