Rewrite : api path를 은닉화
API가 유료거나 사용량에 제한이 있는 경우, API Key를 숨겨야 될 수 있다.
유저가 URL 변화를 볼 수 없다.
설정
: <Link href="/about"> 태그를 눌렀을때 /about 페이지가 아닌 / 페이지로 이동
module.exports = {
async rewrites() {
return [
{
source: '/about',
destination: '/',
},
]
},
}
사용 예제
1) next.config.js 파일에서 rewrites 설정
const API_KEY = process.env.API_KEY;
module.exports = {
async rewrites() {
return [
{
source: "/api/movies",
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
},
];
},
};
2) 기존의 api_key가 노출되는 경로로 api를 호출하지 않아도 데이터를 정상적으로 받아올 수 있다.
// api 호출하는 페이지
import { useEffect, useState } from "react";
export default function Home() {
const [movies, setMovies] = useState();
useEffect(() => {
(async () => {
const { results } = await (await fetch(`/api/movies`)).json();
setMovies(results);
})();
}, []);
return (
<div>api 호출</div>
);
}
'Development > React.js' 카테고리의 다른 글
next - _document.js (0) | 2022.04.14 |
---|---|
next에서의 Data Fetching (0) | 2022.04.14 |
next.config.js로 Redirects 설정 (0) | 2022.04.14 |
next.config.js에서 base path를 설정 (0) | 2022.04.14 |
next.cofing.js 파일에서 환경변수를 설정하는 방법 (0) | 2022.04.14 |