TIL: Next.js (4) redirect, rewrite - 220621

Lumpen·2022년 6월 21일
0

TIL

목록 보기
57/242

Keyword

Next.js

기본적으로 next.js npm run dev를 하면 서버와 클라이언트가 함께 실행됨

redirect

api key를 숨기지 않는다

return 은 배열

redirect 시 url이 변경됨

  1. source를 찾는다
  2. source로 접속시 destination으로 보낸다
  3. permanent: 영구성 설정 - 브라우저나 검색엔진이 정보를 기억하는지 여부

config.js를 설정하면 서버 재시작 필요

결과가 웹사이트 안, 밖 여부에 관계 없이 redirect를 할 수 있다

pattern matching이 가능함

source 뒤에 /:path 를 써주면
dstination 뒤로 /:path가 매칭됨

/:path 뒤에 *을 붙여주면 뒤에 여러 단계의 path가 오더라도 연결됨

// next.config.js
module.exports = {
  reactStrictMode: true,

  async redirects() {
    return [
      {
        source: "/old-blog/:path*",
        destination: "/new-sexy-blog/:path*",
        permanent: false,
      },
    ];
  }
};

rewrite

기존엔 개발자 도구의 네트워크 탭에서 api key를 볼 수 있지만
api key를 숨길 수 있다

return은 배열

새로운 주소로 보내주지면 url을 변경하지 않는다

request를 masking을 한다

// next.config.js
module.exports = {
  reactStrictMode: true,

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

// pages/index.ts
 const { results } = await (await fetch(`/api/movies`)).json();
profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글