フォームとデータミューテーション
フォームを使用すると、Webアプリケーションでデータの作成や更新が可能です。Next.jsではAPI Routesを使用して、フォーム送信とデータミューテーションを強力に処理する方法を提供しています。
知っておくと良いこと:
- 近く、App Routerへの段階的な移行とServer Actionsの使用を推奨する予定です。Server Actionsを使用すると、API Routeを手動で作成せずに、コンポーネントから直接呼び出せる非同期サーバー関数を定義できます。
- API RoutesはデフォルトでCORSヘッダーを指定しません。つまり、同一オリジンに限定されます。
- API Routesはサーバー上で実行されるため、環境変数を通じてAPIキーなどの機密情報をクライアントに公開せずに使用できます。これはアプリケーションのセキュリティにとって重要です。
例
サーバー専用フォーム
Pages Routerでは、サーバー上で安全にデータを変更するために、手動でAPIエンドポイントを作成する必要があります。
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const data = req.body
const id = await createItem(data)
res.status(200).json({ id })
}
export default function handler(req, res) {
const data = req.body
const id = await createItem(data)
res.status(200).json({ id })
}
次に、イベントハンドラーからクライアント側でAPI Routeを呼び出します:
import { FormEvent } from 'react'
export default function Page() {
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">送信</button>
</form>
)
}
export default function Page() {
async function onSubmit(event) {
event.preventDefault()
const formData = new FormData(event.target)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">送信</button>
</form>
)
}
フォームバリデーション
基本的なクライアントサイドのフォームバリデーションには、required
やtype="email"
などのHTMLバリデーションを使用することを推奨します。
より高度なサーバーサイドバリデーションには、zodなどのスキーマバリデーションライブラリを使用して、データ変更前にフォームフィールドを検証できます:
import type { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const parsed = schema.parse(req.body)
// ...
}
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(req, res) {
const parsed = schema.parse(req.body)
// ...
}
エラーハンドリング
フォーム送信が失敗した場合にエラーメッセージを表示するには、Reactのstateを使用します:
import React, { useState, FormEvent } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setIsLoading(true)
setError(null) // 新しいリクエスト開始時に以前のエラーをクリア
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('データの送信に失敗しました。もう一度お試しください。')
}
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
} catch (error) {
// ユーザーに表示するエラーメッセージを取得
setError(error.message)
console.error(error)
} finally {
setIsLoading(false)
}
}
return (
<div>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '読み込み中...' : '送信'}
</button>
</form>
</div>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
async function onSubmit(event) {
event.preventDefault()
setIsLoading(true)
setError(null) // 新しいリクエスト開始時に以前のエラーをクリア
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('データの送信に失敗しました。もう一度お試しください。')
}
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
} catch (error) {
// ユーザーに表示するエラーメッセージを取得
setError(error.message)
console.error(error)
} finally {
setIsLoading(false)
}
}
return (
<div>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '読み込み中...' : '送信'}
</button>
</form>
</div>
)
}
ローディング状態の表示
フォームがサーバーに送信中の場合、Reactのstateを使用してローディング状態を表示できます:
import React, { useState, FormEvent } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false)
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setIsLoading(true) // リクエスト開始時にローディングをtrueに設定
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
} catch (error) {
// 必要に応じてエラーを処理
console.error(error)
} finally {
setIsLoading(false) // リクエスト完了時にローディングをfalseに設定
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '読み込み中...' : '送信'}
</button>
</form>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
async function onSubmit(event) {
event.preventDefault()
setIsLoading(true) // リクエスト開始時にローディングをtrueに設定
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// 必要に応じてレスポンスを処理
const data = await response.json()
// ...
} catch (error) {
// 必要に応じてエラーを処理
console.error(error)
} finally {
setIsLoading(false) // リクエスト完了時にローディングをfalseに設定
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? '読み込み中...' : '送信'}
</button>
</form>
)
}
リダイレクト
ミューテーション後にユーザーを別のルートにリダイレクトしたい場合、redirect
を使用して絶対URLまたは相対URLにリダイレクトできます:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
export default async function handler(req, res) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
Cookieの設定
API Route内でsetHeader
メソッドを使用してCookieを設定できます:
Cookieの読み取り
API Route内でcookies
リクエストヘルパーを使用してCookieを読み取れます:
Cookieの削除
API Route内でsetHeader
メソッドを使用してCookieを削除できます: