0
0

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】redirectのリダイレクトタイプを変更する方法

Posted at

デフォルトのリダイレクトタイプ

Next.jsのredirectは、使用場所によってデフォルトのリダイレクトタイプが異なります。

  • Server Actions: push (ブラウザ履歴に新しいエントリを追加)
  • その他の場所: replace (現在のURLをブラウザ履歴で置き換え)

リダイレクトタイプの変更方法

redirectの第2引数でtypeパラメータを指定することで、デフォルトの動作を上書きできます。

基本的な使い方

import { redirect, RedirectType } from 'next/navigation'

// replaceを使用
redirect('/redirect-to', RedirectType.replace)

// pushを使用
redirect('/redirect-to', RedirectType.push)

注意点

  • Server Componentsではtypeパラメータは効果がありません
  • redirectはエラーをスローするため、try/catchの外で呼び出す必要があります
  • クライアントコンポーネントのイベントハンドラではuseRouterを使用してください

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?