- Server API 만들기
- NextRequest와 NextResponse 사용
- 예시
-
import { NextRequest, NextResponse } from 'next/server'; export async function GET(req: NextRequest) { const { pathname, searchParams, host } = req.nextUrl; return NextResponse.json({ id: 1, name: 'Hong', pathname, str: searchParams.get('str'), ip: req.ip || host, // cookies: req.cookies.getAll(), }); }
- middleware
- app 폴더 속이 아닌 app과 동일한 위치 폴더에 middleware.ts 생성
- ex. src/middleware.ts
- middleware 함수와 config를 export 한다.
- matcher에 해당되는 path일 경우에만 middleware 작동
- 예시
- middleware.ts
import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { console.log('&&&>>', request.cookies); const didLogin = request.cookies.has('nextjs'); if (!didLogin) return NextResponse.redirect(new URL('/photos', request.url)); return NextResponse.next(); } export const config = { matcher: ['/aaa', '/bbb/:path*'], };
- app 폴더 속이 아닌 app과 동일한 위치 폴더에 middleware.ts 생성
728x90
'Front-end > Next.js' 카테고리의 다른 글
[Next.js] Error/Loading/Not-found Page (0) | 2024.03.08 |
---|---|
[Next.js] NextAuth 소셜 로그인, openssl 설치 (0) | 2024.03.08 |
[Next.js] Styling (shadcn/ui 사용) (0) | 2024.03.08 |
[Next.js] Data Fetching (0) | 2024.03.08 |
[Next.js] Link, Routes (0) | 2024.03.08 |