Menu

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

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

補足:

  • まもなく段階的にApp Routerを採用し、フォーム送信とデータミューテーションを処理するためにServer Actionsを使用することをお勧めする予定です。Server Actionsにより、API Routeを手動で作成する必要なく、コンポーネントから直接呼び出すことができる非同期サーバー関数を定義できます。
  • API RoutesはCORSヘッダーを指定しません。つまり、デフォルトではsame-originのみです。
  • API Routesはサーバー上で実行されるため、環境変数を通じてAPIキーなどの機密値を使用でき、クライアントに公開されません。これはアプリケーションのセキュリティにとって非常に重要です。

リダイレクト

ミューテーション後にユーザーを別のルートにリダイレクトする場合は、任意の絶対URLまたは相対URLにredirectできます。

pages/api/submit.ts
TypeScript
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
TypeScript
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
TypeScript
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
TypeScript
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.')
}