Development/React.js

next.config.js 로 Rewrite 하기

moretz0921 2022. 4. 14. 23:18

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>
  );
}