728x90
next.js 13버전 때 학습내용 정리 문서로 현재와 다름 주의
Middleware
middleware.js
루트 디렉토리에 생성가능
타 파일들 layout이나 page가 실행되기전에 실행됨.
Matcher
특정 경로에서만 실행
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};
Next response
NextResponse 를 사용하여 다음을 수행
- redirect : 다른 url로 들어오는 요청
- rewrite : 주어진 url을 표시하며 응답
- API 경로, 목적지에 대한 요청 getServerSideProps rewrite 설정
- 응답 쿠키 설정
- 응답 헤더 설정
쿠키 사용
쿠키는 request:NextRequest에서 받아옴
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')?.value;
console.log(cookie); // => 'fast'
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
헤더설정
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('contents-type', 'application/json');
//...
}
응답 생성
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' } },
);
}
}
고급 미들웨어 플래그
skipTrailingSlashRedirect
뒤에 붙는 / 설정
// next.config.js
module.exports = {
skipTrailingSlashRedirect: true,
};
// middleware.js
const legacyPrefixes = ['/docs', '/blog'];
export default async function middleware(req) {
const { pathname } = req.nextUrl;
if (legacyPrefixes.some((prefix) => pathname.startsWith(prefix))) {
return NextResponse.next();
}
// apply trailing slash handling
if (
!pathname.endsWith('/') &&
!pathname.match(/((?!\.well-known(?:\/.*)?)(?:[^/]+\/)*[^/]+\.\w+)/)
) {
req.nextUrl.pathname += '/';
return NextResponse.redirect(req.nextUrl);
}
}
skipMiddlewareUrlNormalizeURL
URL 정규화 비활성화
// next.config.js
module.exports = {
skipMiddlewareUrlNormalize: true,
};
// middleware.js
export default async function middleware(req) {
const { pathname } = req.nextUrl;
// GET /_next/data/build-id/hello.json
console.log(pathname);
// with the flag this now /_next/data/build-id/hello.json
// without the flag this would be normalized to /hello
}
'공부공부 > Next.js 공식문서' 카테고리의 다른 글
[next.js 공식문서] 12. Static and Dynamic Rendering (0) | 2024.02.29 |
---|---|
[next.js 공식문서] 11. Internationalization (0) | 2024.02.28 |
[next.js 공식문서] 09. Intercepting Routes (0) | 2024.02.27 |
[next.js 공식문서] 08. Parallel Routes (0) | 2024.02.27 |
[next.js 공식문서] 07. Route Handlers (0) | 2024.02.27 |