フォームとデータ更新 (Mutations)
フォームを使用すると、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">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">Submit</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}`)
}
フォーム検証
基本的なフォーム検証には、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)
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>
)
}
エラーハンドリング
フォーム送信が失敗した場合にエラーメッセージを表示するには、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>
)
}
クッキーの設定
APIルート (API Route) 内で setHeader
メソッドを使用してクッキーを設定できます:
クッキーの読み取り
cookies
リクエストヘルパーを使用してAPIルート内でクッキーを読み取れます:
クッキーの削除
APIルート内で setHeader
メソッドを使用してクッキーを削除できます: