본문 바로가기
개발 프레임워크/Next.js

[Nextjs] client의 IP주소를 가져와 비교하여 특정 IP주소에서만 홈페이지 이용을 허용

by minhyeok.lee 2023. 4. 3.
반응형

[Nextjs] client의 IP주소를 가져와 비교하여 dev, qc서버를 허용하고 싶은 IP 주소 (ex. 회사 IP주소 or 집 IP 주소)가 아니라면 리다이렉트하기

 

1. Next.js에서 client의 IP주소를 가져오는 방법

 axios.get("https://geolocation-db.com/json/").then((res) => {
    console.log(res?.data?.IPv4);
  });

 

 

출력값

"내가 사용하고 있는 IP주소가 string 형태로 출력"

 

 

2. router를 사용하여 외부주소로 리다이렉트하는 방법

import { useRouter } from "next/router";

const router = useRouter();
  
router.push("redirect하고 싶은 주소");

 

 

3. 사용해야하는 파일 및 코드

.env 파일

# development || production || test
NEXT_PUBLIC_NODE_ENV=development

 

_app.tsx

  useEffect(() => {
    if (process.env.NEXT_PUBLIC_NODE_ENV !== "production") {
      axios.get("https://geolocation-db.com/json/").then((res) => {
        if (res?.data?.IPv4 !== "허용하고 싶은 IP 주소") {
          router.push("redirect하고 싶은 주소");
        }
      });
    }
  });

위 코드를 사용하여 dev, qc서버를 허용하고 싶은 IP 주소 (ex. 회사 IP주소 or 집 IP 주소)가 아니라면 리다이렉트 한다.

반응형

댓글