next에서는 자체적으로 API를 빌드할 수 있다.
/pages/api/*에 있는 파일들은 페이지가 아닌, api로 동작하며 /api/*의 주소로 매핑 된다.
api 폴더 안에 있는 파일들은 서버사이드에서만 사용되며 클라이언트 번들의 사이즈는 늘리지 않는다.
API 는 default export된 request와 response를 받는 함수로 이루어져 있다.
request는 http.IncomingMessage에 pre-built middlewares가 추가된 값이며
response는 http.ServerResponse에 helper functions가 추가된 값이다.
서로 다른 메소드를 처리하기 위해서는 request.method를 사용할 수 있다.
export default function handler(request: NextApiRequest, response: NextApiResponse){
if(request.method === 'POST'){
// post method
response.status(200).json({method: 'post'})
}else {
// other method
response.status(200).json({method: 'other'})
}
}API Routes는 기본적으로 CORS 헤더를 명시하고 있지 않다. 따라서 same-origin only 정책을 가진다.
이를 해결 하기 위해선 api-routes-cors를 사용하여 해결할 수 있다.
또한 next export와는 함께 사용할 수 없다.
페이지와 동일하게 API도 동적 라우팅을 사용할 수 있다.
/pages/api/post/[postId].ts 형태로 설정하면 아래처럼 받을 수 있다.
export default function handler(req: NextApiRequest, res: NextApiResponse){
const { postId } = req.query
// ...
}만약 /post와 /post/[postId]를 함께 사용하고 싶다면 다음 두 가지 방법으로 가능하다.
/api/post.ts 와 /api/post/[postId].ts 사용/api/post/index.ts 와 /api/post/[postId].ts 사용/api/post/[postId].ts만 사용할 경우 /post/에 대해 postId가 undefined가 되므로, 호출되지 않는다.
/pages/api/post/[...slug] 형태로 사용하면 페이지와 동일하게 하위 값 까지 한번에 가져올 수 있다.
/pages/api/post/a/b/c 는 { slug: ['a', 'b', 'c'] } 형태로 가져온다.
/pages/api/post/[[...slug]]를 사용하면 slug를 이용한 라우팅에 추가로 slug가 비어있는 경우도 처리한다.
| /post/[…slug] | /post/[[…slug]] | |
|---|---|---|
| /post | X | O |
| /post/a | O | O |
| /post/a/b | O | O |
next에는 몇몇 기본 헬퍼를 제공한다.
req.cookies - defaults: {}req.query - defaults: {}req.body - defaults: parsed data or nullnext.config.js
export const config = {
api: {
bodyParser: false
}
}export const config = {
api: {
bodyParser: {
sizeLimit: '500kb', // 1mb, ...
}
}
}export const config = {
api: {
externalResolver: true
// 경로가 'express'나 'connect'같은 external resolver에 의해 처리되고 있음을 뜻한다.
}
}export const config ={
api: {
responseLimit: [false | string] // default: 4mb
// 응답 본문의 최대 용량을 지정한다. ex) 8mb, 300kb, ...
}
}next에는 몇몇 기본 헬퍼를 제공한다.
res.status(code) - code : HTTP Status coderes.json(body) - body : serializable objectres.send(body) - body : string or object or Bufferres.redirect([status, ] path)res.revalidate(path)