Next.js で現在開いているページが Dynamic Route かどうか調べる

現在開いているページが Dynamic Route であるページが調べるにはどうすればよいでしょうか?それは単純にパスを調べるだけでわかります。

// pages/[name]/index.tsx

import { isDynamicRoute } from "next/dist/next-server/lib/router/utils";
  ...
    
const Index: NextPage = () => {
  const router = useRouter();
    if (isDynamicRoute(router.pathname)) {
      // true なら Dynamic Route
    }
    ...
}

isDynamicRoute(...) は Next.js で用意されている関数で、単純な正規表現マッチです。

github.com

Next.js の内部処理を見てみると、同じように Dynamic Route かどうかがチェックされているのがわかります。

github.com