Skip to content

Verify GitLab webhooks

Verify that a webhook really came from GitLab before acting on it.

Identifier 'gitlab'
Import import { verifyGitLab } from 'verihook/gitlab'
Headers webhook-signature, webhook-id, webhook-timestamp (signing token)
x-gitlab-token (secret token)
x-gitlab-event
Signature Signing token (GitLab 19.1+): Standard Webhooks HMAC-SHA256 of <id>.<timestamp>.<raw body>. Secret token (older): the token itself in x-gitlab-token.
Replay window 300 seconds (signing token only) (options.tolerance)
result.eventType the body’s object_kind, or the x-gitlab-event header

The signing token (whsec_...) or the secret token you set on the webhook under Settings → Webhooks in the project or group. Pass whichever one you configured.

Store it in an environment variable (GITLAB_WEBHOOK_SECRET below) and never commit it.

import { verifyGitLab } from 'verihook/gitlab';
export async function POST(request: Request) {
const result = await verifyGitLab(request, process.env.GITLAB_WEBHOOK_SECRET!);
if (!result.valid) {
console.warn(result.code, result.reason, result.hint);
return new Response('Invalid signature', { status: 401 });
}
console.log(result.eventType, result.event);
return Response.json({ received: true });
}

request can be a Fetch Request or { headers, body, url? } with the raw body. verifyWebhook('gitlab', request, secret) from verihook does the same. Read why the raw body matters if verification fails behind a body parser.

app/api/webhooks/gitlab/route.ts
import { createWebhookHandler } from 'verihook/next';
export const POST = createWebhookHandler('gitlab', process.env.GITLAB_WEBHOOK_SECRET!, async (payload, result) => {
// Runs only for a valid signature
console.log(result.eventType, result.event);
});

Each adapter responds 401 to an invalid signature, 413 to a body over maxBodySize (2 MB by default) and 200 to a duplicate when you pass a dedupeStore.

  • Prefer the signing token: the secret token is sent in plain text and doesn’t protect against replays.

signWebhook from verihook/testing builds a correctly signed GitLab request for your tests:

import { signWebhook } from 'verihook/testing';
import { verifyGitLab } from 'verihook/gitlab';
const hook = await signWebhook('gitlab', {
secret: 'gitlab_secret_token',
payload: { id: 'evt_test' },
});
const result = await verifyGitLab(
{ headers: hook.headers, body: hook.body, url: hook.url },
hook.secret,
);
// result.valid === true

From the command line, npx verihook simulate gitlab --url http://localhost:3000/webhooks/gitlab sends one to your local server.

See Testing your handlers for supertest and Fetch Request examples.

Failed results carry a code and often a hint with the likely cause. See Troubleshooting for each error code.

GitLab’s webhook documentation