본문 바로가기
개발/Next.js

middleware.ts

by 안뇽! 2024. 2. 11.
반응형

middleware

middleware는 request가 완료되기 전에 실행된다. 그 후 들어오는 request에 따라 헤더를 다시 작성하거나 리다이렉트를 한다.

 

app폴더와 동일한 레벨에 두어야 한다.

app 폴더 안에 있으면 안된다.

 

// 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))
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}

 

위 코드는 /about/ 에 접근했을때 /home으로 리다이렉트 시키는 middleware.ts 이다.

 

경로 조건

Matcher

matcher에 해당하는 url에 접근할 때 실행된다.

export const config = {
  matcher: '/about/:path*',
}

 

export const config = {
  matcher: ['/about/:path*', '/dashboard/:path*'],
}

 

조건문

/about, /dashboard에 접근했을때 실행된다.

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))
  }
}

 

NextResponse

NextResponse API의 기능은 다음과 같다.

  • redirect
  • rewrite
  • request의 헤더를 설정
  • 응답 쿠키, 응답 헤더 설정

 


참고

https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths

 

Routing: Middleware | Next.js

Learn how to use Middleware to run code before a request is completed.

nextjs.org

 

반응형