4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.jsでRouter.pushを使うときに「No Router instance found」のエラーが発生

Posted at

概要

Next.jsのルーティングの記事にある通り、Next.jsではRouter.pushを使うことでURL履歴のpushとreplaceが可能です。例えば、コンポーネントに渡ってくるプロパティなどをチェックして不備があれば、別のパスに遷移するような使い方が考えられます。
今回はこのRouter.pushを使うときに、「No Router instance found」のエラーが発生するケースがあったので、それについて書いてみたいと思います。

どんなときにエラーが起きるのか

こちらのissueのやりとりにある通り、SSRでRouterのメソッドを使うことはできません。ので、コンポーネントがマウントされる前に呼び出しを行うとエラーが発生します。

対応

上記issueのコメントにある通り、componentDidMountの中で呼び出しを行うか、windowsが読み込まれたタイミングで呼び出しを行えば、エラーが発生するのを防げます。windowsが読み込まれたタイミングで、呼び出しを行う実装サンプルは以下の通りです。

Sample.js
import Router from "next/router";

export default function Sample(prop) {
  if (typeof window !== "undefined") {
    if (!prop.userId) {
      Router.push("/");
    }
  }

  return (
    <div>
      propチェックOK
    </div>
  );
}


4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?