Recent Posts
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
관리 메뉴

개발자 박가나

[250108 TIL] 본캠프 69일차 (MiddleWare) 본문

내일배움캠프

[250108 TIL] 본캠프 69일차 (MiddleWare)

gnchoco97 2025. 1. 8. 21:06

요청이 완료되기 전에 특정 동작을 실행시킬 수 있는 기능을 제공한다.

/* 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));
    }
}