📌 Next.js 에서 redirects와 rewrites 를 변경하기 위해서는 next.config.js 파일에서 작성해야한다.
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async redirects () {
return [
{
source: '/contact',
destination: '/form',
permanent: false,
}
]
}
}
module.exports = nextConfig;
// http://localhost:3002/contact 를 입력하면
// http://localhost:3002/form 로 이동한다.
// 즉 사용자가 URL이 변경되는 것을 확인할 수 있다.
const API_KEY = "abcdefg00000000000000";
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async rewrites () {
return [
{
source: '/api/movies',
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}&language=en-US&page=1`
}
]
}
};
// destination의 주소가 'api/movies'로 마스킹 되었다.
// 그래서 api 키를 노출시키지 않고 사용
module.exports = nextConfig;
// index.js
// 가짜 주소인 api/movies로 마스크 처리 했으므로 fetching 하는 주소도 바꿔준다!
useEffect(() => {
fetch('api/movies')
.then((res) => {
return res.json();
})
.then((data) => {
const { results } = data;
console.log(results);
setMovies(results);
});
}, []);
콘솔창을 열어서 네트워크를 들어가서 확인해도 API key를 노출시키지 않고 마스킹 처리되어서 잘 나오고 있는 것을 확인할 수 있다.
💡 앞서
next.config.js
파일에서 변수에 API Key를 할당해주었는데 이 또한 감추고 싶다면 환경변수를 이용하면 된다.
.env
파일을 생성한다. // .env
API_KEY = abcdefg00000000000000
.gitignore
파일에 .env
파일이 push 되지 않게 해야한다. // .gitignore
.env
next.config.js
로 돌아가서 API Key를 감춰준다. -> process.env
를 앞에 꼭 작성해야한다!// next.config.js
// 환경 변수로 감추기
const API_KEY = process.env.API_KEY;
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async rewrites () {
return [
{
source: '/api/movies',
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}&language=en-US&page=1`
}
]
}
}
module.exports = nextConfig