request
에 마스크 씌우는 것과 같습니다.next.config.js
파일을 이용하여 유저가 특정 url-path
로 접근을 시도할때 서버에 설정된 곳으로 redirect
시켜주는 것입니다.https://localhost:3000/contact
로 접근을 시도하면 httpas://localhost:3000/form
pattern-matching
도 지원합니다.pattern-matching
: url-path
만 지정한 url 로 바꿔주고 query
는 그대로둡니다.next.config.js
파일에 NextJS 에서 제공하는 redirects
키워드를 사용합니다.
redirects
키워드는 객체배열을 반환하고 각 객체는 NextJS 에서 정한 키들을 사용하여 동작합니다. (source, destination, permanent)
soruce
: 유저가 입력한 url-path
or query
destination
: 서버에서 유저를 보내줄 1) url-path
or 2) 다른 호스트의 urlpermanent
: 현재 리디렉션이 영구적인지 아닌지 boolean 값으로 적용합니다, 영구적인지 아닌지에 따라 상태코드, 캐시 등의 차이점이 발생합니다.코드 예시
*
: *
이후에 어떤 url이라도 그대로 가져옵니다.//// pattern-matching X
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async redirects() {
return [
{
source: "/contact",
destination: "/form",
permanent: false,
},
];
},
};
module.exports = nextConfig;
//// pattern-matching
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
async redirects() {
return [
{
source: "/old-blog/:path*",
destination: "/new-sexy-blog/:path*",
permanent: false,
},
];
},
};
module.exports = nextConfig;
유저 URL 입력 ("/old-blog/1231241241?bar=1234")
리디렉션된 URL ("/new-sexy-blog/1231241241?bar=1234")
redirect
시키지만 URL 은 바뀌지 않아서 유저가 알 수 없습니다.redirecs
와 대부분 동일 합니다.rewrites
를 활용해서 가짜 API url 을 만들어 주고 컴포넌트에서 가짜 API url 을 사용하면 API key 를 숨길 수 있습니다..env
파일에서 관리해주면 더 완벽하게 API key 를 숨겨줄 수 있습니다.// next.config.js
const API_KEY = process.env.API_Key;
const nextConfig = {
...(생략)
async redirects() {...(생략)
},
async rewrites() {
return [
{
source: "/api/movies",
destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
},
];
},
...(생략)
// /pages/index.js
...(생략)
export default function Home() {
const [movies, setMovies] = useState();
useEffect(() => {
(async () => {
const { results } = await (await fetch(`/api/movies`)).json();
// console.log(data);
// console.log(results);
setMovies(results);
})();
}, []);
...(생략)
// .env
API_KEY = "b9a221486250d0601edc38**********"
노마드코더 NextJS 시작하기
NextJS 공식문서