1
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?

More than 1 year has passed since last update.

【Next.js】404エラーの際に外部サイトの404ページを使いたい!(App Router)

Posted at

はじめに

存在しないページにアクセスしたときに、自作の404ページではなく、外部サイトの404ページを使いたい!って方向けの記事です。

(この記事の通りに作りたい人ってどれくらいいるんですかね?)

実装

まず、App Routerでは存在しないURLへのアクセス時に呼び出されるnot-found.tsxというファイルがあります。
File Conventions: not-found.js

これを、appフォルダ直下(パスが「/」のpage.tsxが存在する階層)に設置します。
例)

.
└── app
    ├── page.tsx
    ├── layout.tsx
    └── not-found.tsx # ココ!

そして、not-found.tsx内に404ページを作っていくのですが、外部サイトのページがいい!って頑固者のためにredirectという機能を使います。
Functions: redirect

詳しいことは公式リファレンスを見れば一発なので、実装だけ載せておきます。

not-found.tsx
import { redirect } from 'next/navigation';

export default function NotFound() {
  redirect(遷移したい外部サイトのURL)
}

これだけです。記述が少なくてシンプルですね!

1
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
1
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?