Published on

Nextjs - middleware

Authors
  • avatar
    Name
    Inhwan Cho
    Twitter

Middleware란?

Nextjs에서 페이지가 랜더링되기 전에 서버에서 실행되는 코드입니다. Middleware에서는 RequestResponse에 접근하여 부가적인 처리 및 변경이 가능합니다.

주로 로그인 관련 인증 확인에 사용합니다.

사용 방법

  • 파일 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 사용 방법

  1. MUST start with /
  2. Can include named parameters: /about/:path matches /about/a and /about/b but not /about/a/c
  3. 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
  4. Can use regular expression enclosed in parenthesis: /about/(.*) is the same as /about/:path*

참고

공식문서