Client
[Next.js] Rewrite 사용하기
니용
2022. 1. 12. 09:58
반응형
이번 글에서는 우리의 api path 를 은닉화 할 수 있는 rewrite 에 대해 설명드리고자 합니다.
next.config.js 파일에서 이전에 redirects() 를 생성했던 것과 마찬가지로, rewrites() 를 생성합니다.
async rewrites() {
return [
{
}
]
}
위에 옵션은 마찬가지로 source, destination 이 들어가게 됩니다.
이전에 프로젝트를 기본으로 만들었을 때 localhost:3000/api/hello 로 들어가게 되면 api 가 호출되는 것을 확인할 수 있었습니다. 여기는 get 방식으로 api 를 호출하여 json 의 포맷으로 가져오게 되는데, 이 부분을 은닉화해보려고 합니다.
소스가 이런 형태로 되어있다고 가정합니다.
/** @type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
async redirects() {
return [
{
source: "/oldpath/:path*",
destination: "/newpath/:path*",
permanent: false,
}
]
},
async rewrites() {
return [
{
source: "/api/abbo",
destination: "/api/hello"
}
]
}
}
명령어 npm run dev 를 입력하면 3000 포트가 사용중이신 분들은 3001로 출력됩니다.
그리고 http://localhost:3001/api/abbo 로 링크를 들어가게 되면
즉, 우리는 위의 rewrite 옵션을 사용하여 /api/hello 라는 API 를 숨길 수 있게 되었습니다.
참고링크: https://nextjs.org/docs/api-routes/introduction
API Routes: Introduction | Next.js
Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works here.
nextjs.org
반응형