- 문제: 동일 페이지를 다시 클릭했을 때 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로 여러 번 이동 요청이 발생.
발생 원인: 동일 URL로 이동하려는 요청을 방지하지 않았음.
해결: 현재 URL과 이동하려는 URL을 비교하여, 동일할 경우 이동을 차단.
import { useRouter } from "next/router";
const handleNavigation = (path: string) => {
const router = useRouter();
if (router.pathname !== path) {
router.push(path);
}
};
발생 원인: 사용자가 같은 페이지를 클릭했을 때 특별한 동작이 없음.
해결: 동일 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);
}
};
발생 원인: 동일 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}`);
};
발생 원인: Next.js의 router.push가 현재 URL에 대해 동작하지 않음.
해결: router.replace()를 사용해 강제로 새로고침 없이 페이지를 다시 렌더링.
import { useRouter } from "next/router";
const handleNavigation = (path: string) => {
const router = useRouter();
router.replace(path); // 강제 URL 변경 처리
};
문제: 동일 페이지로의 중복 네비게이션 시 에러 발생.
발생 원인:
해결 방안:
필요한 동작에 맞게 위 해결 방안을 적용하면 동일 URL 클릭 시 원하는 동작을 구현할 수 있습니다. 😊