はじめに/ガイド/フォーム

API Routesを使用したフォーム作成方法

フォームを使用すると、ウェブアプリケーションでデータの作成や更新が可能です。Next.jsではAPI Routesを使用してデータ変更を強力に処理できます。このガイドでは、サーバー側でフォーム送信を処理する方法を説明します。

サーバーフォーム

サーバー側でフォーム送信を処理するには、データを安全に変更する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 })
}

次に、クライアント側からイベントハンドラで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>
  )
}

知っておくと便利:

  • API RoutesはCORSヘッダーを指定しないため、デフォルトで同一オリジンのみ許可されます。
  • API Routesはサーバー側で実行されるため、環境変数を使用してAPIキーなどの機密情報をクライアントに公開せずに利用できます。これはアプリケーションのセキュリティ上重要です。

フォームバリデーション

基本的なクライアントサイドのフォームバリデーションには、requiredtype="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)
  // ...
}

エラーハンドリング

フォーム送信が失敗した場合にエラーメッセージを表示するには、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('Failed to submit the data. Please try again.')
      }

      // 必要に応じてレスポンスを処理
      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 ? 'Loading...' : 'Submit'}
        </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 ? 'Loading...' : '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}`)
}

On this page