コンテンツにスキップ
アプリケーションの構築データフェッチフォームとミューテーション

フォームとミューテーション

フォームを使用すると、ウェブアプリケーションでデータを作成および更新できます。Next.jsは、**API Routes**を使用してフォームの送信とデータのミューテーションを処理する強力な方法を提供します。

知っておくと良いこと

  • 近いうちに、App Routerを段階的に採用し、フォームの送信とデータのミューテーションの処理にはサーバーアクションを使用することを推奨します。サーバーアクションを使用すると、コンポーネントから直接呼び出すことができる非同期サーバー関数を定義でき、APIルートを手動で作成する必要がありません。
  • API RoutesはCORSヘッダーを指定しないため、デフォルトでは同一オリジンのみです。
  • API Routesはサーバー上で実行されるため、環境変数を介して(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のstateを使用してエラーメッセージを表示できます。

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のstateを使用してローディング状態を表示できます。

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または相対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}`)
}

クッキーの設定

API Route内で、レスポンスの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.')
}

クッキーの読み取り

API Route内で、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
  // ...
}

クッキーの削除

API Route内で、レスポンスの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.')
}