티스토리 뷰

NextJS

[NextJS] Redirect and Rewrite

BIBLIYA 2022. 10. 14. 17:21

Redirect

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  async redirects() {
    return [
      {
        source: "/이렇게 친다면",
        destination: "/여기로 보내줘",
        permanent: false,
      },
    ];
  },
};

module.exports = nextConfig;

 

1. source를 찾는다 ( /find로 이동한다면)

유저가 어디론가 이동한다면 원하는 곳으로 destination으로 보낸다 ( /about 으로 가게 해줘)

2. redirection이 영구적(permanent)인지 아닌지에 따라 브라우저나 검색엔진이 정보를 기억하는지 안 하는지 결정된다.

 

Pattern matching

/** @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;

Rewrite

rewrite는 redirects랑 다르다. 

redirects는 url로 갈때 새로운 url로 가는 것을 알 수 있는데

rewrite는 유저를 redirect 시키기는 하지만 url은 변하지 않는다

API 숨길때 많이 사용

 

// next.config.js

/** @type {import('next').NextConfig} */
const API_KEY = "~~~";

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

module.exports = nextConfig;
useEffect(() => {
    (async () => {
      const { results } = await (await fetch(`/api/movies`)).json();
      setMovies(results);
    })();
  }, []);

 

.env 파일에 숨긴 다음 진행해도 됨

// .env
API_KEY= ~~~

// next.config.js
const API_KEY = process.env.API_KEY;

 

'NextJS' 카테고리의 다른 글

[NextJS] Dynamic Routes  (0) 2022.10.17
[NextJS] Server Side Rendering  (0) 2022.10.14
[NextJS] _app  (0) 2022.10.14
[NextJS] Styles JSX  (0) 2022.10.14
[NextJS] CSS Modules  (0) 2022.10.14
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/04   »
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 29 30
글 보관함