- Published On
Next.js - middleware
Middleware란?
Nextjs에서 페이지가 랜더링되기 전에
서버에서 실행되는 코드입니다.
Middleware에서는 Request
와 Response
에 접근하여
부가적인 처리 및 변경이 가능합니다.
주로 로그인 관련 인증 확인에 사용합니다.
사용 방법
- 파일
pages
경로 밖에/app/middleware.ts(js)
을 생성합니다. - 최신버전에서는
_middleware.ts
로 사용하면 실행되지 않습니다. config의 matcher
를 커스텀하여 원하는 경로에 미들웨어를 적용합니다.
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}
//matcher allows you to filter Middleware to run on specific paths.
matchers 사용 방법
- MUST start with
/
- Can include named parameters:
/about/:path
matches/about/a
and/about/b
but not/about/a/c
- Can have modifiers on named parameters (starting with
:
):/about/:path*
matches/about/a/b/c
because * is zero or more.?
is zero or one and+
one or more - Can use regular expression enclosed in parenthesis:
/about/(.*)
is the same as/about/:path*
참고
이전 포스트
cn function다음 포스트
Next.js - route handler연관된 포스트 구경가기
1. Next.js 란?2. Next.js - middleware3. Next.js - route handler4. Next.js Pages Router5. Next.js(pages-router) - data fetching6. Next.js - dynamic import7. Next.js에서 Head 컴포넌트 사용 방법8. Next.js의 폴더 구조 분석9. Next.js에서 메타데이터 다루기10. Next.js(app-router) - data fetching11. Next.js runtime12. Next.js 패러렐 라우트, 인터셉팅 라우트13. Next.js에서 Font를 설정하는 방법14. Next.js - Server Actions15. Next.js Image 컴포넌트16. Next.js 빌드 과정과 Webpack, Babel17. Next.js Configuration: next.config.mjs18. Next.js 커스텀 서버19. Next.js의 렌더링 과정
간략히