NextJS 시작 #10 | Redirects and Rewrites

HyeonWooGa·2022년 8월 7일
0

NextJS Intro

목록 보기
11/16

API key 를 숨기는 이유

  • 유료 결제한 API key 일 수 있음
  • API 사용 횟수가 제한되는 경우가 있음
  • API key 를 누군가 남용할 수도 있음

Redirects & Rewrites

  • request 에 마스크 씌우는 것과 같습니다.

Redirects

Redirects 정의

  • next.config.js 파일을 이용하여 유저가 특정 url-path 로 접근을 시도할때 서버에 설정된 곳으로 redirect 시켜주는 것입니다.
    • 예를 들어 유저가 https://localhost:3000/contact 로 접근을 시도하면 httpas://localhost:3000/form
  • pattern-matching 도 지원합니다.
    • pattern-matching : url-path 만 지정한 url 로 바꿔주고 query 는 그대로둡니다.

Redirects 방법

  1. next.config.js 파일에 NextJS 에서 제공하는 redirects 키워드를 사용합니다.

  2. redirects 키워드는 객체배열을 반환하고 각 객체는 NextJS 에서 정한 키들을 사용하여 동작합니다. (source, destination, permanent)

    • soruce : 유저가 입력한 url-path or query
    • destination : 서버에서 유저를 보내줄 1) url-path or 2) 다른 호스트의 url
    • permanent : 현재 리디렉션이 영구적인지 아닌지 boolean 값으로 적용합니다, 영구적인지 아닌지에 따라 상태코드, 캐시 등의 차이점이 발생합니다.
  3. 코드 예시

  • * :
    • * 이후에 어떤 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;
  1. Pattern-Matching 동작 예시
  • 유저 URL 입력 ("/old-blog/1231241241?bar=1234")

  • 리디렉션된 URL ("/new-sexy-blog/1231241241?bar=1234")


Rewrites

Rewrites 정의

  • 유저를 redirect 시키지만 URL 은 바뀌지 않아서 유저가 알 수 없습니다.

Rewrites 방법

  • redirecs 와 대부분 동일 합니다.
  • rewrites 를 활용해서 가짜 API url 을 만들어 주고 컴포넌트에서 가짜 API url 을 사용하면 API key 를 숨길 수 있습니다.
  • 추가로 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 를 사용하면 생산성부분에서 큰 장점이 있을 것이라고 생각됩니다.
  • NextJS 는 클라이언트, 서버 모두 커버하는 프레임워크인데 서버 부분은 Express 와 어떤 차이점이 있고 강점이 있을 지 궁금합니다.
  • NextJS 기초를 마치고 이력서, 포트폴리오 제작 후에 당근마켓 클론코딩을 하며 더 공부해보겠습니다.

참조

노마드코더 NextJS 시작하기
NextJS 공식문서

profile
Aim for the TOP, Developer

0개의 댓글