5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsで `/` から別ページにリダイレクトしたいときにハマった話

Posted at

こんにちは!

今回は、Next.js で開発しているときに 「トップページ(/)にアクセスされたら自動で別ページに飛ばしたい」 という要件に直面したので、そのときのハマりポイントと解決方法をまとめます。

発生した問題

あるとき、
「ユーザーが / にアクセスしたら /hello-nextjs にリダイレクトしたい」
という単純そうな要件がありました。

最初は React Router のノリで書こうとして…

<Switch>
  <Route path="/hello-nextjs" component={HelloNextjs} />
  <Redirect to="/hello-nextjs" />
</Switch>

みたいにしたくなるんですが、Next.jsにはreact-routerは不要なのでこれはNGでした。

「じゃあどうするんだろう?」と調べてみると、Next.jsのバージョンによって色々なやり方があることが分かりました。


解決方法

✅ App Router(Next.js 13以降)

App Router を使っている場合はめちゃ簡単です。
サーバーコンポーネントなら redirect を呼ぶだけ。

// app/page.tsx
import { redirect } from "next/navigation";

export default function HomePage() {
  redirect("/hello-nextjs");
}

これで / にアクセスした瞬間に /hello-nextjs に飛びます。


✅ Client Component でやる場合

クライアント側でやりたいときは useRouteruseEffect を使います。

"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";

export default function HomePage() {
  const router = useRouter();

  useEffect(() => {
    router.push("/hello-nextjs");
  }, [router]);

  return <div>Redirecting...</div>;
}

これだと一瞬「Redirecting…」が見えますが、実装はシンプル。


✅ Pages Router(Next.js 12まで)

古いプロジェクトだと getServerSideProps でリダイレクトできます。

// pages/index.tsx
export const getServerSideProps = () => {
  return {
    redirect: {
      destination: "/hello-nextjs",
      permanent: false,
    },
  };
};

export default function Home() {
  return null;
}

SSRなので、ユーザー側にはリダイレクトが自然に行われます。


まとめ

  • Next.js 13+ (App Router)redirect を使うのが一番シンプル
  • Client ComponentuseRouter + useEffect
  • Pages Router (〜v12)getServerSideProps

最初は「なんでReact Routerのやり方じゃできないんだ!」とハマりましたが、バージョンごとのやり方を知ってしまえば安心です。

Qiita見てるみなさんの中にも「Next.jsでリダイレクトどうやるんだろ?」って迷う方がいると思うので、少しでも参考になれば嬉しいです!🙌

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?