페이지를 완전히 렌더링 하기 전에 코드를 실행할 수 있음.
예시로, 특정 페이지에 따른 리다이렉팅, 응답헤더 작성 등등이 가능함.
미들웨어 실행 순서
프로젝트의 모든 경로 에 대해 미들웨어가 호출됨 . 실행 순서는 다음과 같음.
1.
next.config.js 의 header 부분
2.
next.config.js 의 redirects 부분
3.
미들웨어( rewrites ,redirects , 기타 등등)
4.
next.config.js 의 beforeFiles(rewrites)
5.
파일 시스템 경로( public/ , _next/static/ , pages/, app/)
6.
next.config.js 의 afterFiles(rewrites)
7.
동적 경로( /blog/[slug])
8.
next.config.js 의 fallback(rewrites)
미들웨어 구현 경로
•
src 폴더 하위 middleware.ts
구현 예시)
import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) {
console.log("미들웨어가 실행되고 있음! 체크중!@@");
if (request.nextUrl.pathname.startsWith("/products/1004")) {
console.log("미들웨어 - 경로를 리다이렉팅함!");
return NextResponse.redirect(new URL("/products", request.url));
}
}
export const config = {
matcher: ["/products/:path*"],
};
TypeScript
복사
matcher
특정 경로에서 실행되도록 미들웨어를 필터링할 수 있다.
export const config = {
matcher: '/about/:path*',
// matcher: ['/about/:path*', '/dashboard/:path*'], // 다중 matcher 사용 예
}
TypeScript
복사
macther 사용되는 문자열은 정규표현식 기반에 따름.
/products/:path* path가 있거나(많거나) 없거나 둘 다 가능
/products/:path+ path가 하나 또는 많거나
cookie
•
Request시에는 쿠키 헤더에 저장
•
Response에서는 Set-Cookie 헤더에 저장.
•
Next.js는 NextRequest 및 NextResponse의 쿠키 확장을 통해 이러한 쿠키에 액세스하고 조작할 수 있는 편리한 방법을 제공.
Request 경우, 쿠키에는 다음과 같은 메서드가 제공
•
get, getAll, set, delete
•
has를 사용하여 쿠키의 존재 여부를 확인하거나 clear를 사용하여 모든 쿠키를 제거할 수 있음.
Response의 경우 쿠키에는 get, getAll, set, delete 메서드가 있습니다.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Assume a "Cookie:nextjs=fast" header to be present on the incoming request
// Getting cookies from the request using the `RequestCookies` API
let cookie = request.cookies.get('nextjs')
console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
const allCookies = request.cookies.getAll()
console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
request.cookies.has('nextjs') // => true
request.cookies.delete('nextjs')
request.cookies.has('nextjs') // => false
// Setting cookies on the response using the `ResponseCookies` API
const response = NextResponse.next()
response.cookies.set('vercel', 'fast')
response.cookies.set({
name: 'vercel',
value: 'fast',
path: '/',
})
cookie = response.cookies.get('vercel')
console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/test` header.
return response
}
TypeScript
복사
header
v13 부터 가능.
요청 및 응답 헤더를 미들웨어에서 설정 가능하다.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello')
return response
}
TypeScript
복사
응답 생성
Response또는 인스턴스를 반환하여 미들웨어에서 직접 응답이 가능함.
import { NextRequest, NextResponse } from 'next/server'
import { isAuthenticated } from '@lib/auth'
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
}
export function middleware(request: NextRequest) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new NextResponse(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
)
}
}
TypeScript
복사