✍ 공부/NextJS

[ TIL ] Next.js redirects와 rewrites로 API key 숨기기

Po_tta_tt0 2022. 3. 18. 21:17
반응형

 

 

 

 

 API KEY

개요

API 키(KEY) 는 인증(Authentication) 방식의 한 종류이다.

API 키 이외의 인증방식으로는 API 토큰(Token) 방식이 있다.

 

특징

API 키는 특정 사용자만 알 수 있는 문자열이다.

개발자는 API 제공사의 페이지에서 키를 발급받아 호출 시 API 키를 이용하여 호출한다.

 

단점

모든 클라이언트가 같은 API 키를 공유하기 때문에 보안에 취약할 수 있다.

 

 

 

 

✍ next.config.js

 

redirects와 rewrites는 둘 다 루트 디렉토리에 있는 next.config.js에서 사용할 수 있는 함수이다.

next.config.js는 설정 파일로 클라이언트의 접근 경로를 우회하여 전송해주는 방법을 명시 / 설정하는 파일이다.

 

 

📌 redirects

 

다른 페이지로 사용자를 이동시키고 싶으면 사용할 수 있는 함수다.

 

<next.config.js>

/** @type {import('next').NextConfig} */
const API_KEY = process.env.NEXT_PUBLIC_API_KEY;
const nextConfig = {
  reactStrictMode: true,
  async redirects() {
    return [
      {
        source: "/old-blog/:path*", // ✨ 1
        destination: "/new-sexy-blog/:path*", // ✨ 2
        permanent: false, // ✨ 3
      },
    ];
  },
};

✨ : 봐야 할 곳 표시

 

STEP

1. source : source를 찾는다 

2. destination : 유저가 향하게 될 목적지 경로를 설정한다.

3. permanent : redirection이 영구적인지 아닌지 여부를 결정한다.

 - 영구적일 경우 브라우저나 검색엔진이 이 정보를 저장할 수 있다.

4. terminal에서 서버를 재시작하라는 알림을 확인한다. 

 - > Found a change in next.config.js. Restart the server to see the changes in effect.

5. 재시작한다

 

 

특징

우리의 웹페이지 내부든 외부든 redirect 할 수 있다.

유저가 URL이 변하는 것을 확인할 수 있다.

 

 

 

📌 rewrites

 

다른 페이지로 사용자를 이동시키고 싶으면 사용할 수 있는 비동기 함수다

source와 destination이 들어있는 배열을 return 한다.

  • source: String - is the incoming request path pattern.
  • destination: String is the path you want to route to.
  • basePath: false or undefined - if false the basePath won't be included when matching, can be used for external rewrites only.
  • locale: false or undefined - whether the locale should not be included when matching.
  • has is an array of has objects with the type, key and value properties.

 

<next.config.js>

/** @type {import('next').NextConfig} */
const API_KEY = process.env.NEXT_PUBLIC_API_KEY;
const nextConfig = {
  reactStrictMode: true,
  async rewrites() { // ✨ 1
    return [
      {
        source: "/api/movies", // ✨ 2
        destination: `https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}`, // ✨ 3
      },
      {
        source: "/api/movies/:id", // ✨ 2
        destination: `https://api.themoviedb.org/3/movie/:id?api_key=${API_KEY}`, // ✨ 3
      },
    ];
  },
};

module.exports = nextConfig;

✨ : 봐야 할 곳 표시

 

STEP

1. source : source를 찾는다 

2. destination : 유저가 향하게 될 목적지 경로를 설정한다.

3. terminal에서 서버를 재시작하라는 알림을 확인한다. 

 - > Found a change in next.config.js. Restart the server to see the changes in effect.

4. 재시작한다

 

 

특징

우리의 웹페이지 내부든 외부든 redirect 할 수 있다.

유저가 URL의 변화를 확인할 수 없다.

개발자가 의도한 경로로만 접근가능하다.

 

 

 

 

 

 숨긴 데이터 가져오기

 

<공식문서>

Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with 
Server-side Rendering
 or 
Static Generation
, and updating or creating content at runtime with 
Incremental Static Regeneration

정적데이터를 가져오는지 / 페이지 요청시에 렌더되는 데이터인지에 따라

 

getStaticProps 

- 빌드시 고정. 수정 불가능

getStaticPath

- 동적라우팅 + getStaticProps를 원할 때 사용

getServerSideProps

- 페이지 요청시마다 데이터를 가져온다.

 

로 구분할 수 있다.

 

 

 

예시

<index.js> (원하는 component에 추가로 넣어준다)

export async function getServerSideProps() { // ✨ 1
  const { results } = await (
    await fetch(`http://localhost:3000/api/movies`)
  ).json(); // ✨ 2
  return {
    props: {
      results, // ✨ 3
    },
  };
}

  // 1.  async는 하고 싶으면 하고 말고싶으면 말면 됨

  // 2.  rewrites로 연결된 source를 fetch시킨다

  // 3.  이 props에 { results }값이 들어간다. 그리고 이 results는 props로 전달된다.
+ return하는 object는 props라고 불리는 key 혹은 property를 가진다.

 

<index.js>

export default function Home({ results }) {

index.js에 results가 전달된다. == 데이터가 전달된다.

 

 

 

특징

  • 이 자리에 어떤 코드를 짜든 그 코드는 server 쪽에서만 작동한다. (backEnd에서 실행됨)
  • 이를 이용하여 API key를 숨길 수도 있다
  • 무엇을 return하던지, 그 값을 props로서 page에 주게 된다
  • fetch하는 주소는 서버에서 작동할 수 있어야 하기 때문에 http부터 추가해줘야 한다

 

 

 

 

 

 

🙇‍♀️ SUPER THANKS

https://nomadcoders.co/nextjs-fundamentals/lobby 

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

https://nextjs.org/docs/basic-features/data-fetching/overview#getstaticprops-static-generation

https://dongwooklee96.github.io/post/2021/03/28/rest-api-%EB%B3%B4%EC%95%88-%EB%B0%8F-%EC%9D%B8%EC%A6%9D-%EB%B0%A9%EC%8B%9D/

https://abbo.tistory.com/265

 

 

 

반응형