# 署名検証のための生の本文の取得方法：Express・Next.js・Hono・FastAPI・Django・Rails・Laravel・Go

> Webhook の署名検証に必要な生の本文を、Express・Next.js・Hono・FastAPI・Django・Rails・Laravel・Go で取得して検証する最小のコードと、よくある落とし穴をまとめます。

公開日: 2026-11-14
Source: https://webhookadmin.com/blog/webhook-raw-body-by-framework/

## 要点

- 署名は届いたバイト列に対して計算されるので、JSON の parser より前に、Webhook の経路だけ生の本文を受け取ります。
- Express は express.raw、Next.js の App Router は request.text()、FastAPI は await request.body()、Django は request.body、Rails は request.raw_post、Laravel は $request->getContent()、Go は io.ReadAll(r.Body) です。
- よくある落とし穴は、全体に JSON の parser を掛けている、文字列に変換するときに文字コードや改行が変わる、CSRF の保護で拒否される、の 3 つです。

Webhook の署名は、送る側が送ったバイト列に対して計算されます。受ける側で JSON に変換してから文字列に戻すと、空白やキーの順番、数値や Unicode の書き方が変わり、署名が合わなくなります。対策は、JSON の parser より前に、Webhook の経路だけ届いたままの本文を受け取ることです。この記事では、8 つのフレームワークでの取得方法と検証の最小のコードを並べます。

例は、Webhook Admin が使う [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md) の形式（`webhook-id`・`webhook-timestamp`・`webhook-signature`）で書きます。Node は npm の `webhookadmin`、Python・Ruby・Go は Standard Webhooks の公式のライブラリ、PHP は標準の関数で検証します。Stripe や GitHub の署名でも、生の本文の取得方法は同じです。各フレームワークの記述は 2026-09-27 に公式のドキュメントで確認しました。

## 早見表

| フレームワーク | 生の本文 | 型 |
|---|---|---|
| Express | `express.raw()` を付けた経路の `req.body` | Buffer |
| Next.js（App Router） | `await request.text()` | string |
| Next.js（Pages Router） | `bodyParser: false` にして本文を読む | Buffer |
| Hono | `await c.req.text()` | string |
| FastAPI | `await request.body()` | bytes |
| Django | `request.body` | bytes |
| Rails | `request.raw_post` | String |
| Laravel | `$request->getContent()` | string |
| Go（net/http） | `io.ReadAll(r.Body)` | []byte |

## Express

[body-parser](https://github.com/expressjs/body-parser) の `raw` は、本文を Buffer のまま `req.body` に含めます。`type` の既定は `application/octet-stream` なので、`application/json` を指定します。`limit` の既定は 100kb です。

```ts
import express from 'express';
import { Webhook } from 'webhookadmin';

const wh = new Webhook(process.env.WEBHOOK_SECRET!);
const app = express();

// Webhook の経路を express.json() より前に置く
app.post('/webhooks', express.raw({ type: 'application/json', limit: '1mb' }), async (req, res) => {
  try {
    const event = await wh.verify(req.body, req.headers);
    res.sendStatus(204);
  } catch {
    res.sendStatus(400);
  }
});

app.use(express.json()); // ほかの経路用
```

`app.use(express.json())` が先にあると、Webhook の経路でも本文が先に変換されます。Stripe のトラブルシューティングも、`express.json()` を Webhook の経路の後に置くよう書いています。

## Next.js（App Router）

Route Handler は Web 標準の `Request` を受け取るので、`request.text()` で本文を文字列として読めます。Next.js のドキュメントは Webhook の受け取りの例でこの形を使い、Pages Router と違って bodyParser の設定は要らないと書いています（[Next.js の route.js](https://nextjs.org/docs/app/api-reference/file-conventions/route)）。

```ts
// app/webhooks/route.ts
import { Webhook } from 'webhookadmin';

const wh = new Webhook(process.env.WEBHOOK_SECRET!);

export async function POST(request: Request) {
  const body = await request.text();
  try {
    const event = await wh.verify(body, request.headers);
    return new Response(null, { status: 204 });
  } catch {
    return new Response('invalid signature', { status: 400 });
  }
}
```

`request.json()` を先に呼ぶと本文を読み切ってしまい、同じ `Request` から本文をもう一度読めません。検証が済んでから、`JSON.parse(body)` か `verify` の戻り値を使います。

## Next.js（Pages Router）

Pages Router の API Routes は本文を自動で変換します。Next.js のドキュメントは、Webhook の生の本文を検証するために `bodyParser` を `false` にする例を挙げています（[API Routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes)）。

```ts
// pages/api/webhooks.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { Webhook } from 'webhookadmin';

export const config = { api: { bodyParser: false } };
const wh = new Webhook(process.env.WEBHOOK_SECRET!);

async function readRaw(req: NextApiRequest): Promise<Buffer> {
  const chunks: Buffer[] = [];
  for await (const chunk of req) chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);
  return Buffer.concat(chunks);
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const raw = await readRaw(req);
  try {
    await wh.verify(raw, req.headers);
    res.status(204).end();
  } catch {
    res.status(400).end();
  }
}
```

## Hono

Hono の `c.req.text()` は本文を文字列で、`c.req.arrayBuffer()` は ArrayBuffer で返します（[Hono の HonoRequest](https://hono.dev/docs/api/request)）。Cloudflare Workers・Bun・Deno・Node のどれでも同じ書き方です。

```ts
import { Hono } from 'hono';
import { Webhook } from 'webhookadmin';

const app = new Hono<{ Bindings: { WEBHOOK_SECRET: string } }>();

app.post('/webhooks', async (c) => {
  const wh = new Webhook(c.env.WEBHOOK_SECRET); // Workers では c.env から読む
  const body = await c.req.text();
  try {
    await wh.verify(body, c.req.raw.headers);
    return c.body(null, 204);
  } catch {
    return c.text('invalid signature', 400);
  }
});

export default app;
```

検証の前に、本文を読むバリデーター（`zValidator('json', …)` など）を同じ経路に付けないようにします。

## FastAPI

FastAPI の `Request` は Starlette の `Request` で、`await request.body()` が bytes を返します（[FastAPI のドキュメント](https://fastapi.tiangolo.com/advanced/using-request-directly/)）。本文を Pydantic のモデルとして引数で受けると、変換後の値しか手に入りません。

```python
import os
from fastapi import FastAPI, Request, Response
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["WEBHOOK_SECRET"])  # whsec_…
app = FastAPI()

@app.post("/webhooks")
async def webhooks(request: Request):
    body = await request.body()  # bytes
    try:
        event = wh.verify(body, dict(request.headers))
    except Exception:
        return Response(status_code=400)
    return Response(status_code=204)
```

## Django

`HttpRequest.body` は「生の HTTP の要求の本文の bytes」です（[Django のドキュメント](https://docs.djangoproject.com/en/stable/ref/request-response/)）。先に `request.read()` などで本文を読むと、その後の `request.body` は `RawPostDataException` になります。Webhook の経路は CSRF の検査から除外します。

```python
import os
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["WEBHOOK_SECRET"])

@csrf_exempt
@require_POST
def webhooks(request):
    try:
        event = wh.verify(request.body, dict(request.headers))
    except Exception:
        return HttpResponse(status=400)
    return HttpResponse(status=204)
```

## Rails

`request.raw_post` は本文を文字列で返します（[ActionDispatch::Request](https://api.rubyonrails.org/classes/ActionDispatch/Request.html)）。Standard Webhooks の Ruby のライブラリの README も、Rails の例でこの値を渡しています。`ActionController::Base` を継承したコントローラーでは、Webhook の経路を CSRF の保護から除外します。

```ruby
class WebhooksController < ApplicationController
  protect_from_forgery except: :create

  def create
    webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
    payload = webhook.verify(request.raw_post, {
      'webhook-id' => request.headers['webhook-id'],
      'webhook-timestamp' => request.headers['webhook-timestamp'],
      'webhook-signature' => request.headers['webhook-signature'],
    })
    head :no_content
  rescue StandardWebhooks::WebhookVerificationError
    head :bad_request
  end
end
```

## Laravel

Laravel の `Request` は Symfony の `Request` を継承していて、`getContent()` が本文をそのまま返します（[Symfony の HttpFoundation](https://symfony.com/doc/current/components/http_foundation.html)）。Webhook の経路は `bootstrap/app.php` の `validateCsrfTokens(except: [...])` で CSRF の検査から除外します。Laravel のドキュメントも Stripe の Webhook を例にこの設定を説明しています（[Laravel の CSRF](https://laravel.com/docs/12.x/csrf)）。下の例はライブラリを使わずに検証しています。各工程の意味は[Standard Webhooks の仕様と実装の記事](https://webhookadmin.com/blog/standard-webhooks-explained/)で説明しています。

```php
use Illuminate\Http\Request;

Route::post('/webhooks', function (Request $request) {
    $body = $request->getContent();
    $id = (string) $request->header('webhook-id');
    $ts = (string) $request->header('webhook-timestamp');
    if (!ctype_digit($ts) || abs(time() - (int) $ts) > 300) {
        return response('', 400);
    }
    $key = base64_decode(substr(env('WEBHOOK_SECRET'), strlen('whsec_')));
    $expected = base64_encode(hash_hmac('sha256', "{$id}.{$ts}.{$body}", $key, true));
    foreach (explode(' ', (string) $request->header('webhook-signature')) as $part) {
        [$version, $sig] = array_pad(explode(',', $part, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $sig)) {
            return response('', 204);
        }
    }
    return response('', 400);
});
```

## Go（net/http）

サーバーが受けた要求の `r.Body` は常に nil ではなく、本文が無ければすぐ EOF を返します。大きすぎる本文を読まないよう、`http.MaxBytesReader` で上限を付けてから読みます（[net/http](https://pkg.go.dev/net/http)）。

```go
package main

import (
	"io"
	"net/http"
	"os"

	standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"
)

func main() {
	wh, err := standardwebhooks.NewWebhook(os.Getenv("WEBHOOK_SECRET"))
	if err != nil {
		panic(err)
	}
	http.HandleFunc("POST /webhooks", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
		if err != nil {
			http.Error(w, "too large", http.StatusRequestEntityTooLarge)
			return
		}
		if err := wh.Verify(body, r.Header); err != nil {
			http.Error(w, "invalid signature", http.StatusBadRequest)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})
	http.ListenAndServe(":3000", nil)
}
```

## よくある落とし穴

1. **全体に JSON の parser を掛けている**。Express の `app.use(express.json())`、NestJS の既定の設定、Hono や FastAPI のバリデーターなど、経路より先に本文を読む仕組みがあると、生の本文は手に入りません。NestJS は `NestFactory.create(AppModule, { rawBody: true })` で起動すると `req.rawBody` で受け取れます（[NestJS のドキュメント](https://docs.nestjs.com/faq/raw-body)）。
2. **文字列に変換するときに中身が変わる**。UTF-8 以外で読む、改行を正規化する、前後の空白を取り除く、といった処理が途中に入ると署名は合いません。bytes のまま渡すか、UTF-8 でそのまま文字列にします。
3. **CSRF の保護で拒否される**。Rails・Django・Laravel は、フォームの送信を守るために POST に CSRF のトークンを求めます。Webhook の送る側はトークンを送れないので、Webhook の経路だけ削除します。Stripe のドキュメントも同じ注意を書いています。

## 手元での確認方法

1. 検証の前に、受け取った本文の長さと SHA-256 を記録する。
2. 送る側の配信の記録や手元の送信のスクリプトで、送った本文の SHA-256 を計算する。
3. 2 つが一致すれば、生の本文は取得できています。一致しなければ、途中で本文が変換されています。
4. 本文が一致しているのに検証が失敗するなら、鍵か署名する中身が違います。切り分けの手順は[署名検証が失敗する原因の記事](https://webhookadmin.com/blog/webhook-signature-verification-failed/)にまとめました。

手元の受け口に署名付きの本文を送って試す方法は[ローカルで試す方法の記事](https://webhookadmin.com/blog/test-webhooks-locally/)にあります。Webhook Admin の署名の形式と各言語のライブラリは[署名検証のドキュメント](https://webhookadmin.com/docs/sdk/#libraries)と[始め方の署名の検証](https://webhookadmin.com/docs/#verify)にあります。

受け側がどの言語でも公式のライブラリで検証できる形式で Webhook を送りたい場合は、Webhook Admin を無料で試せます（月 5 万通まで）。[https://app.webhookadmin.com/signup](https://app.webhookadmin.com/signup)

## よくある質問

### Next.js の App Router ではどう受け取りますか。

Route Handler で await request.text() を呼びます。Next.js のドキュメントも Webhook の受け取りの例で request.text() を使っていて、Pages Router のような bodyParser の設定は要らないと書いています。

### Express で 1 つの経路だけ生の本文で受けるにはどうしますか。

その経路のミドルウェアに express.raw({ type: 'application/json' }) を指定し、app.use(express.json()) はその経路より後に登録します。req.body は Buffer になるので、そのまま検証に渡します。

### Python では bytes と str のどちらを渡しますか。

受け取った bytes をそのまま渡すのが確実です。FastAPI の await request.body() と Django の request.body はどちらも bytes を返します。Standard Webhooks の Python のライブラリは bytes を受け取ると UTF-8 として読みます。
