コンテンツにスキップ

API Routes でフォームを作成する方法

フォームは、Webアプリケーションでデータを作成および更新できるようにします。Next.js は、API Routes を使用してデータミューテーションを処理するための強力な方法を提供します。このガイドでは、サーバーでフォーム送信を処理する方法を説明します。

サーバーフォーム

サーバーでフォーム送信を処理するには、データを安全にミューテーションする 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 Route を呼び出します。

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>
  )
}

知っておくと良いこと

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

フォームのバリデーション

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