Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

pgg-dev

[NextJs] Redirect / Rewrite 본문

Next.js

[NextJs] Redirect / Rewrite

pgg-dev 2022. 8. 20. 19:32

api 키 숨기기

사용량 제한 및 유료, 남용할 경우를 대비해 숨겨야한다

 

inspect network탭에서 request한 url을 확인할수있다

또한 api key까지 확인할수있다

 

비공개를 위한 방법

Next.js에서 커스텀 설정을 하기 위해서는 프로젝트 디렉터리의 루트(package.json 옆)에 next.config.js 또는 next.config.mjs 파일을 만들 수 있습니다.

next.config.js는 JSON 파일이 아닌 일반 Node.js 모듈입니다.

Next.js 서버 및 빌드 단계에서 사용되며 브라우저 빌드에는 포함되지 않습니다.

https://nextjs.org/docs/api-reference/next.config.js/introduction

 

Redirects (URL변경됨)

Redirect을 사용하면 들어오는 request 경로를 다른 destination 경로로 Redirect할 수 있습니다. Redirect을 사용하려면 next.config.js에서 redirects 키를 사용할 수 있습니다.

 

redirects은 source, destination 및 permanent 속성이 있는 객체를 포함하는 배열을 반환하는 비동기 함수입니다.

source: 들어오는 request 경로 패턴 (request 경로)

destination: 라우팅하려는 경로 (redirect할 경로)

permanent: true인 경우 클라이언트와 search 엔진에 redirect를 영구적으로 cache하도록 지시하는 308 status code를 사용하고, false인 경우 일시적이고 cache되지 않은 307 status code를 사용합니다.

https://nextjs.org/docs/api-reference/next.config.js/redirects

 

Rewrites (URL변경되지 않음)

Rewrites를 사용하면 들어오는 request 경로를 다른 destination 경로에 매핑할 수 있습니다.

Rewrites은 URL 프록시 역할을 하고 destination 경로를 mask하여 사용자가 사이트에서 위치를 변경하지 않은 것처럼 보이게 합니다. 반대로 redirects은 새 페이지로 reroute되고 URL 변경 사항을 표시합니다.

https://nextjs.org/docs/api-reference/next.config.js/rewrites

 

Movie Poster Path

https://image.tmdb.org/t/p/w500/${movie.poster_path}

 

주의! fetch /api/movies 또는 http://localhost:3000/api/movies 가능하지만 http 아닌 https fetch하게 되면 오류가 발생합니다.

next.config.js 

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/contact",
        destination: "/form",
        permanent: false,
      },
    ];
  },
};

http://localhost:3000/contact -> http://localhost:3000/form 리다이렉트 됨

 

현재 주소 내에서든, 다른 주소로든 모두 리다이렉트 가능한다.

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/contact",
        destination: "https://www.naver.com/",
        permanent: false,
      },
    ];
  },
};

 

http://localhost:3000/contact -> 네이버로 이동됨

 

patten matching도 지원한다

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/old/:path",
        destination: "/new/:path",
        permanent: false,
      },
    ];
  },
};

http://localhost:3000/old/123 -> http://localhost:3000/new/123

 

주소 뒤에 *를 붙여주면 모든 걸 catch 할수있다

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/old/:path*",
        destination: "/new/:path*",
        permanent: false,
      },
    ];
  },
};

http://localhost:3000/old/123/blog/5678 -> http://localhost:3000/new/123/blog/5678

new로만 바뀌고 뒤에 path는 모두 그대로 유지

 

리다이렉트 할 주소를 여러개 설정 가능하다

const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/old/:path*",
        destination: "/new/:path*",
        permanent: false,
      },
      {
        source: "/start",
        destination: "/end",
        permanent: false,
      },
    ];
  },
};

 

 

rewrites

const nextConfig = {
  reactStrictMode: true,
  async rewrites() {
    return [
      {
        source: "/api/movies",
        destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`,
      },
    ];
  },
};

기존에 fetching하던 request주소를 destination에 적어주면, sorce의 주소로 덮어써진다.

코드내에 요청주소를 source 주소로 바꿔야한다

nextjs 가 request를 masking 한다

변경된 주소로 request 및 response를 잘받아온다

Comments