FrontEnd/Next.js
[Next.js] Next.js API 만들기 (feat. handler, withHandler)
위그든씨
2023. 1. 22. 16:00
Next.js에서 제공하는 api 기능을 이용해서, api 서버를 만들고 orm을 통해 실제 DB와 연결시키는 것이 목적
1. Next.js api 기능 이용
- pages 디렉터리 구조가 router가 되듯이 pages 폴더 안에 api 폴더를 생성한다.
- api폴더를 생성 후 그 안에 파일을 작성하면 api url이 된다.
import { NextApiRequest, NextApiResponse } from "next";
import withHandler from '../../libs/server/withHandler'
async function handler(req: NextApiRequest, res: NextApiResponse) {
//... 로직
res.status(200).json({ ok: true })
}
export default withHandler("GET", handler)
withHandler 함수의 목적은 handler에서 동일하게 발생하는 보일러 플레이트를 줄이기 위함.
예를 들어, method 검증이나 로그인/비로그인 상태에 따라 redirect 시키는 로직 등등
handler 함수는 마지막에 res.status(200).json({ ok: true }) 를 통해 client에게 응답을 해줄 수 있다.
// withHandler 내부 구조
import { useState } from "react";
import { NextApiRequest, NextApiResponse } from "next";
export interface ResponseType {
[key: string]: any;
ok: boolean;
}
export default function withHandler(
method: "POST" | "GET" | "DEL" | "PUT",
fn: (req: NextApiRequest, res: NextApiResponse) => void
) {
return async function (req: NextApiRequest, res: NextApiResponse) {
if (req.method !== method) {
return res.status(405).end();
}
try {
fn(req, res);
} catch (e) {
return res.status(500).json({ e });
}
};
}