フォームとデータ変更 (Mutations)

フォームを使用すると、ウェブアプリケーションでデータの作成や更新が可能になります。Next.js では、API ルートを使用してフォーム送信とデータ変更を処理する強力な方法を提供しています。

知っておくと良いこと:

  • 近い将来、App Router の段階的な採用とフォーム送信・データ変更処理にServer Actionsの使用を推奨する予定です。Server Actions を使用すると、API ルートを手動で作成する必要なく、コンポーネントから直接呼び出せる非同期サーバー関数を定義できます。
  • API ルートはデフォルトで CORS ヘッダーを指定しません。つまり、同一オリジンでのみ動作します。
  • API ルートはサーバー上で実行されるため、クライアントに公開せずに環境変数を通じて(API キーなどの)機密情報を使用できます。これはアプリケーションのセキュリティにおいて重要です。

リダイレクト

データ変更後にユーザーを別のルートにリダイレクトしたい場合、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}`)
}

API ルート内でsetHeaderメソッドを使用してCookieを設定できます:

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が設定されました。')
}

API ルート内でcookiesリクエストヘルパーを使用してCookieを読み取れます:

import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const auth = req.cookies.authorization
  // ...
}

API ルート内でsetHeaderメソッドを使用してCookieを削除できます:

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が削除されました。')
}

On this page