Next.jsでリダイレクトをマスターしてユーザー体験を向上させる
Next.jsで別のページへリダイレクトする方法
Next.jsでは、さまざまな方法で別のページへリダイレクトすることができます。
next.config.jsを使う
Next.jsプロジェクトのルートディレクトリにある next.config.js
ファイルを使用して、リダイレクトを設定することができます。
module.exports = {
redirects: async () => {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
]
},
}
この例では、/old-page
にアクセスすると、301ステータスコードと共に /new-page
へリダイレクトされます。
getStaticProps
または getServerSideProps
関数を使用して、ページごとにリダイレクトを設定することができます。
export async function getStaticProps() {
// ここにリダイレクトのロジックを記述
if (condition) {
return {
redirect: {
destination: '/new-page',
permanent: true,
},
}
}
return {
props: {},
}
}
この例では、condition
が真の場合、/new-page
へリダイレクトされます。
redirect
関数は、ページコンポーネント内で直接リダイレクトを設定するために使用することができます。
const MyPage = () => {
// ここにリダイレクトのロジックを記述
if (condition) {
return <Redirect to="/new-page" />
}
return (
<div>
<h1>My Page</h1>
</div>
)
}
Middlewareを使う
Next.js 12.1以降では、Middlewareを使用してリダイレクトを設定することができます。
export default function middleware(req, res) {
// ここにリダイレクトのロジックを記述
if (condition) {
return NextResponse.redirect('/new-page')
}
return NextResponse.next()
}
各方法にはそれぞれメリットとデメリットがあります。
プロジェクトの要件に合わせて、最適な方法を選択してください。
Next.js リダイレクト サンプルコード
next.config.js を使う
module.exports = {
redirects: async () => {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
{
source: '/about',
destination: '/company',
statusCode: 302,
},
]
},
}
この例では、以下のリダイレクトを設定しています。
/old-page
は/new-page
へ301ステータスコードと共にリダイレクトされる
getStaticProps または getServerSideProps を使う
export async function getStaticProps() {
const user = await getUser()
if (!user) {
return {
redirect: {
destination: '/login',
permanent: false,
},
}
}
return {
props: {
user,
},
}
}
この例では、ユーザーがログインしていない場合、/login
へリダイレクトされます。
redirect 関数を使う
const MyPage = () => {
const [isAuthorized, setIsAuthorized] = useState(false)
useEffect(() => {
const fetchData = async () => {
const user = await getUser()
setIsAuthorized(!!user)
}
fetchData()
}, [])
if (!isAuthorized) {
return <Redirect to="/login" />
}
return (
<div>
<h1>My Page</h1>
</div>
)
}
Middleware を使う
export default function middleware(req, res) {
const { pathname } = req.url
if (pathname === '/admin') {
const user = await getUser()
if (!user || !user.isAdmin) {
return NextResponse.redirect('/')
}
}
return NextResponse.next()
}
この例では、/admin
にアクセスするユーザーが管理者ではない場合、ホームページへリダイレクトされます。
上記はあくまでもサンプルコードであり、実際のプロジェクトに合わせてコードを変更する必要があります。
Next.js リダイレクト:その他の方法
useRouter
Hookを使用して、現在のページのURLを取得し、リダイレクトを設定することができます。
const MyPage = () => {
const router = useRouter()
useEffect(() => {
if (condition) {
router.push('/new-page')
}
}, [])
return (
<div>
<h1>My Page</h1>
</div>
)
}
window.location
オブジェクトを使用して、JavaScriptから直接リダイレクトを設定することができます。
if (condition) {
window.location.href = '/new-page'
}
アンカータグの href
属性にリダイレクト先のURLを指定することで、リダイレクトを設定することができます。
<a href="/new-page">新しいページへ</a>
Next.jsでリダイレクトを設定するには、さまざまな方法があります。
html reactjs routes