📚 NextJS에서 API Route 작성 시 주의사항
NextJS에서는
/pages/api폴더 내의 모든 파일이/api/*에 매핑되며 페이지 대신 API 엔드포인트로 처리된다. 이는 서버 측 전용 번들이며 클라이언트 측 번들 크기를 늘리지 않는다.
- NextJS에서 API Route를 작동하려면
req, res를 매개변수로 받는 함수를 기본값으로 내보내야(export default)한다.import type { NextApiRequest, NextApiResponse } from 'next'; // export default function handler(req: NextApiRequest, res: NextApiResponse) { //함수를 기본값으로 내보내면 //누군가 이 api에 접속했을 때 NextJS가 이 함수를 호출하여 //아래 코드를 실행한다. if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method } }
- 함수를 기본값으로 내보내야(
export default) 누군가 그 api에 접속했을 때 NextJS가 그 함수를 호출할 수 있다.
API Route 작동 시, NextJS는 handler 함수의 아래 코드를 실행하여 http method에 따라 요청을 보낸다.
if (req.method === 'POST') {
// Process a POST request
} else {
// Handle any other HTTP method
}
위 코드를 반환하는 고차 함수를 만들어 좀 더 유연하게 API Route를 사용할 수 있게 만들어 보자.
📚 참고
고차 함수: 함수를 인자로 받거나, 함수를 리턴하는 함수
export default withHandler("POST", handler);import withHandler from "@/libs/server/withHandler";
import { NextApiRequest, NextApiResponse } from "next";
async function handler(req: NextApiRequest, res: NextApiResponse) {
//form정보 정상적으로 받고 있는지 확인하기 위해 콘솔로그 찍어보자
console.log(req.body);
return res.status(200).end();
}
//withHandler(HTTP 메소드, handler 함수)
export default withHandler("POST", handler);
import { NextApiRequest, NextApiResponse } from "next";
//http method와 fn(req,res)를 인자로 받는 헬퍼 함수 withHandler
//withHandler 함수는 고차 함수
export default function withHandler(
method: "GET" | "POST" | "DELETE",
fn: (req: NextApiRequest, res: NextApiResponse) => void
) {
//사용자가 api request를 보내면 nextJS가 실행할 fn을 반환해줘야 한다.
return async function (req: NextApiRequest, res: NextApiResponse) {
//내가 원하는 메소드가 아닌 경우
if (req.method !== method) {
return res.status(405).end();
//req.method를 서버에서 알고 있지만
//제거되었고 사용할 수 없는 경우(허용되지 않은 메서드 사용 시): 405
//이렇게 하면 handler 펑션을 bad request로 부터 보호할 수 있다.
} try {
await fn(req, res);
//외부에서 인자로 보낸 handler 펑션 실행
} catch (error) {
console.log(error);
return res.status(500).json({ error });
//서버 에러: 500
}
};
}
껍데기인 withHandler 함수로 nextJS가 실행할 함수를 감싸서 좀더 유연하게 api route 코드 재사용 가능하게 만들기 ㅇㅇㅇㅇㅇ! 가 목적