/pages/api/{routeName} -> /app/{apiName}/routes.ts METHOD typesswitch 의 사용이 더 이상 필요 없음 import { NextResponse } from 'next/server'
export const GET = async() => {
...
}
export const POST = async() => {
...
}
export const PUT = async() => {
...
}
export const DELETE = async() => {
...
}
Statically 검증되는 경우
GET 을 사용할 때 기본적으로 statically 검증statically라는 말은 SSG개념으로 빌드 시에 실행 후 데이터를 가져온다robots.txt, rss.xml, sitemap.xml 과 같이 빌드 import { NextResponse } from 'next/server'
export const GET = async() => {
const res = await fetch('...', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY
}
})
const data = await res.json()
return NextResponse.json({ data })
}
Dynamically 검증되는 경우
GET을 제외한 다른 METHOD는 경우GET 을 사용할 때 기본적으로 statically 검증하지만 Request 를 파라미터로 받는 경우dynamically하게 검증된다cookies, headers와 같은 Dynamic Functions 사용하는 경우import { NextResponse } from 'next/server'
export const GET = async(request: Request) => {
const { searchParams } = new URL(request.url)
const id = searchParams.get('id')
const res = await fetch(`.../${id}`, {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY
}
})
const data = await res.json()
return NextResponse.json({ data })
}
route & page 혼합 사용 규칙route 파일은 은 가장 낮은 레벨의 라우팅이며 page 파일처럼 layout과 client-side naviagation에 관여하지 않는다route 파일은 page 파일은 해당 경로의 모든 HTTP 동사를 책임지며 같은 경로에 사용하면 Conflict가 일어난다api 와 화면 중 하나만 관리할 수 있는 경로가 된다| Pages | Route | Result |
|---|---|---|
app/page.js | app/route,js | ❌ Conflict |
app/page.js | app/api/route,js | ✅ Valid |
app/[user]/page.js | app/api/route,js | ✅ Valid |