フォームとミューテーション
フォームを使用すると、ウェブアプリケーションでデータを作成および更新できます。Next.jsは、**APIルート**を使用してフォーム送信とデータミューテーションを処理するための強力な方法を提供します。
知っておくと良い点
- 近日中に、App Routerを段階的に採用し、フォーム送信とデータミューテーションの処理にはServer Actionsを使用することをお勧めします。Server Actionsを使用すると、コンポーネントから直接呼び出すことができる非同期サーバー関数を定義でき、APIルートを手動で作成する必要がなくなります。
- APIルートはCORSヘッダーを指定しません。つまり、デフォルトでは同一オリジンのみとなります。
- APIルートはサーバー上で実行されるため、環境変数を使用して機密値(APIキーなど)を使用でき、クライアントに公開する必要がありません。これは、アプリケーションのセキュリティにとって非常に重要です。
例
サーバー専用フォーム
Pages Routerを使用する場合、サーバー上でデータを安全に更新するために、APIエンドポイントを手動で作成する必要があります。
pages/api/submit.ts
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 })
}
次に、イベントハンドラーを使用してクライアントからAPIルートを呼び出します
pages/index.tsx
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,
})
// Handle response if necessary
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
)
}
フォーム検証
基本的なクライアントサイドのフォーム検証には、required
やtype="email"
などのHTML検証を使用することをお勧めします。
より高度なサーバーサイド検証を行うには、zodなどのスキーマ検証ライブラリを使用して、データを更新する前にフォームフィールドを検証します。
pages/api/submit.ts
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)
// ...
}
エラー処理
Reactの状態を使用して、フォーム送信が失敗したときにエラーメッセージを表示できます。
pages/index.tsx
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) // Clear previous errors when a new request starts
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('Failed to submit the data. Please try again.')
}
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Capture the error message to display to the user
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 ? 'Loading...' : 'Submit'}
</button>
</form>
</div>
)
}
読み込み状態の表示
フォームがサーバーに送信されている間、読み込み状態を表示するには、Reactの状態を使用できます。
pages/index.tsx
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) // Set loading to true when the request starts
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Handle error if necessary
console.error(error)
} finally {
setIsLoading(false) // Set loading to false when the request completes
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
)
}
リダイレクト
ミューテーション後にユーザーを別のルートにリダイレクトしたい場合は、redirect
を使用して、絶対または相対URLにリダイレクトできます。
pages/api/submit.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
Cookieの設定
APIルート内でCookieを設定するには、レスポンスのsetHeader
メソッドを使用できます。
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Set-Cookie', 'username=lee; Path=/; HttpOnly')
res.status(200).send('Cookie has been set.')
}
Cookieの読み取り
APIルート内でCookieを読み取るには、cookies
リクエストヘルパーを使用できます。
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
// ...
}
Cookieの削除
APIルート内でCookieを削除するには、レスポンスのsetHeader
メソッドを使用できます。
pages/api/cookie.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Set-Cookie', 'username=; Path=/; HttpOnly; Max-Age=0')
res.status(200).send('Cookie has been deleted.')
}
役に立ちましたか?