LoginSignup
26
18

More than 3 years have passed since last update.

next.js でページリダイレクト

Last updated at Posted at 2019-10-08

軽くハマったので書いておきます。
もしかしたら間違えてるかもしれないので、その場合は指摘してもらえると :pray:
react-hooks 前提です。
next.js@9 で確認しています。
今後変わる可能性があるのでご了承を。

CSR によるリダイレクト

pushState/replaceState でリダイレクトする。
render の中で next/router を使う。

import { useRouter } from 'next/router';

const HogePage = () => {
  const router = useRouter();

  // pushState の場合
  router.push('/');

  // replaceState の場合
  router.replace('/');

  return <div />;
};

SSR によるリダイレクト

HTTP header でリダイレクトする。
getInitialProps でやる。

HogePage.getInitialProps = async ({ res }) => {
  if (res) {
    res.writeHead(302, { Location: '/' });
    res.end();
  }
}
26
18
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
26
18