Next 페이지 라우터 "attempted to hard navigate to the same URL" 간단한 트러블 슈팅

송연지·2025년 1월 3일
0

트러블슈팅

목록 보기
12/32

문제 발생

- 문제: 동일 페이지를 다시 클릭했을 때 Next.js에서 "attempted to hard navigate to the same URL" 에러가 발생.
- 현상: 동일한 URL(/meeting)로 네비게이션하려고 할 때 오류가 발생하거나, 아무런 동작이 실행되지 않음.

Error: Invariant: attempted to hard navigate to the same URL /meeting http://localhost:3000/meeting
    at handleHardNavigation (webpack-internal:///./node_modules/next/dist/shared/lib/router/router.js:374:15)
    at Router.handleRouteInfoError (webpack-internal:///./node_modules/next/dist/shared/lib/router/router.js:968:13)
    at Router.getRouteInfo (webpack-internal:///./node_modules/next/dist/shared/lib/router/router.js:1192:25)
    at async Router.change (webpack-internal:///./node_modules/next/dist/shared/lib/router/router.js:719:29)

발생 원인

- 중복 네비게이션 요청:
이미 현재 페이지에 머물러 있는 상태에서 동일 URL로의 이동 요청이 발생.
router.push 또는 next/link가 동일 URL로 다시 이동하려고 시도하면서 Next.js가 이를 "잘못된 네비게이션"으로 처리.

- Next.js 동작 특성:
Next.js는 클라이언트 사이드 네비게이션에서 현재 URL과 동일한 URL로 이동을 허용하지 않음.
이는 불필요한 렌더링이나 네트워크 요청을 방지하기 위한 Next.js의 기본 동작.

- 클릭 이벤트 중복 호출:
이벤트 리스너가 중복으로 호출되거나, 잘못된 논리로 인해 동일 URL로 여러 번 이동 요청이 발생.

해결 방안

1. 동일 URL 중복 네비게이션 방지

발생 원인: 동일 URL로 이동하려는 요청을 방지하지 않았음.
해결: 현재 URL과 이동하려는 URL을 비교하여, 동일할 경우 이동을 차단.

import { useRouter } from "next/router";

const handleNavigation = (path: string) => {
  const router = useRouter();
  if (router.pathname !== path) {
    router.push(path);
  }
};

2. 같은 URL 클릭 시 특정 동작 처리

발생 원인: 사용자가 같은 페이지를 클릭했을 때 특별한 동작이 없음.
해결: 동일 URL 클릭 시 상태를 초기화하거나, 페이지를 새로고침.

  • 상태 초기화:
import { useRouter } from "next/router";
import { useState } from "react";

const Navigation = () => {
  const router = useRouter();
  const [refreshKey, setRefreshKey] = useState(0);

  const handleNavigation = (path: string) => {
    if (router.pathname === path) {
      setRefreshKey((prev) => prev + 1); // 상태 초기화
    } else {
      router.push(path);
    }
  };

  return (
    <nav>
      <button onClick={() => handleNavigation("/meeting")}>Go to Meeting</button>
    </nav>
  );
};
  • 페이지 새로고침:
const handleNavigation = (path: string) => {
  if (window.location.pathname === path) {
    window.location.reload(); // 페이지 새로고침
  } else {
    router.push(path);
  }
};

3. 쿼리 파라미터 추가로 재요청 처리

발생 원인: 동일 URL 요청이 Next.js에서 무시됨.
해결: 쿼리 파라미터를 추가하여 동일한 URL이라도 다른 요청처럼 처리.

import { useRouter } from "next/router";

const handleNavigation = (path: string) => {
  const router = useRouter();
  const uniqueKey = new Date().getTime(); // 유니크 값 생성
  router.push(`${path}?refresh=${uniqueKey}`);
};

4. Next.js 기본 동작 활용 (replace 사용)

발생 원인: Next.js의 router.push가 현재 URL에 대해 동작하지 않음.
해결: router.replace()를 사용해 강제로 새로고침 없이 페이지를 다시 렌더링.

import { useRouter } from "next/router";

const handleNavigation = (path: string) => {
  const router = useRouter();
  router.replace(path); // 강제 URL 변경 처리
};

결론

  • 문제: 동일 페이지로의 중복 네비게이션 시 에러 발생.

  • 발생 원인:

    • 동일 URL로 강제 이동 시도.
    • Next.js의 기본 동작으로 동일 URL 이동을 허용하지 않음.
  • 해결 방안:

    • URL 비교를 통해 중복 네비게이션 방지.
    • 상태 초기화, 페이지 새로고침, 쿼리 파라미터 추가 등 원하는 동작 처리.
    • router.replace를 활용해 동일 URL 처리.

필요한 동작에 맞게 위 해결 방안을 적용하면 동일 URL 클릭 시 원하는 동작을 구현할 수 있습니다. 😊

profile
프론트엔드 개발쟈!!

0개의 댓글