# Verify Linear webhooks

Linear signs each webhook so you can confirm that it came from Linear and wasn't changed. The `Linear-Signature` header holds a hex HMAC-SHA256 of the raw body, keyed with the webhook's signing secret, and the body's `webhookTimestamp` lets you reject replays. `LinearWebhookClient` in `@linear/sdk` makes both checks for you.

Agent skill: `npx skills add hookdeck/webhook-skills --skill linear-webhooks` ([details](https://hookdeck.com/webhooks/linear/skill))

> Independent reference generated from hookdeck/webhook-registry (commit a24c8d9, 19 Nov 2026). [Linear's official docs](https://linear.app/developers/webhooks).

[Overview](https://hookdeck.com/webhooks/linear) · [Webhook events (23)](https://hookdeck.com/webhooks/linear/events) · [MCP events](https://hookdeck.com/webhooks/linear/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/linear/verify) · [Production guide](https://hookdeck.com/webhooks/linear/guide-duplicates-ordering-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/linear/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `Linear-Signature` Format: <hex> | [Linear docs](https://linear.app/developers/webhooks) |
| Scheme | `HMAC-SHA256` | [Linear docs](https://linear.app/developers/webhooks) |
| Signed material | `{raw body}` The request body as sent, with nothing added. webhookTimestamp is a field in that body, so the signature covers it. | [Linear docs](https://linear.app/developers/webhooks) |
| Replay window | `1 minutes` Linear recommends this check rather than enforcing it, so your handler makes it. Compare the body's `webhookTimestamp`, in Unix milliseconds, with your clock. | [Linear docs](https://linear.app/developers/webhooks) |
| What to build | `Recompute a digest over the raw body and compare` | [Linear docs](https://linear.app/developers/webhooks) |
| Key | `shared secret` | [Linear docs](https://linear.app/developers/webhooks) |

## Linear webhook secret

Each webhook has its own signing secret, on the webhook's detail page. It isn't your API key or an OAuth app's client secret. Keep it in an environment variable, not in source code.

- Workspace webhooks: open the webhook's detail page under Settings, Administration, API. Viewing it takes workspace admin rights.
- OAuth apps: the app's settings page has a webhook signing secret, separate from its client secret. Linear creates a webhook for each organization that authorizes the app.
- From the API: `webhookCreate` takes a `secret`, and Linear generates one if you leave it out. It is also a field on the `Webhook` type.
- Format: Linear's docs give no format or prefix, so treat it as an opaque string.
- Rotation: the `webhookRotateSecret` mutation returns a new secret and invalidates the old one at once. An OAuth app's Rotate secret control also takes effect immediately, so update your handler at the same moment.

Source: [Linear docs](https://linear.app/developers/webhooks)

## Code

### Express

From [webhook-skills: skills/linear-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/linear-webhooks/examples/express/src/index.js)

```javascript
// Generated with: linear-webhooks skill
// https://github.com/hookdeck/webhook-skills

require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

const app = express();

// Reject deliveries whose webhookTimestamp is more than 1 minute away
// from the server's clock (Linear's recommended replay-protection window).
const WEBHOOK_TIMESTAMP_TOLERANCE_MS = 60 * 1000;

/**
 * Verify a Linear webhook signature.
 *
 * Linear computes HMAC-SHA256 over the raw request body using the webhook's
 * signing secret and sends the hex-encoded digest in the `Linear-Signature`
 * header. The header value is a bare hex string — there is no `sha256=`
 * prefix.
 *
 * @param {Buffer} rawBody - Raw request body
 * @param {string} signatureHeader - Linear-Signature header value
 * @param {string} secret - Linear webhook signing secret
 * @returns {boolean}
 */
function verifyLinearWebhook(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) {
    return false;
  }

  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  try {
    return crypto.timingSafeEqual(
      Buffer.from(signatureHeader, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    // Buffer.from with bad hex (or different lengths in timingSafeEqual)
    return false;
  }
}

/**
 * Check whether a Linear `webhookTimestamp` (UNIX milliseconds) is within the
 * accepted tolerance of the server's clock. Linear recommends rejecting
 * deliveries older than 1 minute to prevent replay attacks.
 */
function isFreshTimestamp(webhookTimestamp, now = Date.now()) {
  if (typeof webhookTimestamp !== 'number') {
    return false;
  }
  return Math.abs(now - webhookTimestamp) <= WEBHOOK_TIMESTAMP_TOLERANCE_MS;
}

// Linear webhook endpoint — must use raw body for signature verification.
app.post(
  '/webhooks/linear',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const signature = req.headers['linear-signature'];
    const event = req.headers['linear-event'];
    const deliveryId = req.headers['linear-delivery'];

    // 1. Verify the signature against the raw body.
    if (!verifyLinearWebhook(req.body, signature, process.env.LINEAR_WEBHOOK_SECRET)) {
      console.error('Linear webhook signature verification failed');
      return res.status(400).send('Invalid signature');
    }

    // 2. Parse the payload only after verifying.
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch (err) {
      console.error('Linear webhook payload is not valid JSON');
      return res.status(400).send('Invalid JSON');
    }

    // 3. Reject stale deliveries.
    if (!isFreshTimestamp(payload.webhookTimestamp)) {
      console.error('Linear webhook timestamp is outside the 1 minute window');
      return res.status(400).send('Stale webhook');
    }

    const action = payload.action;
    console.log(`Received Linear ${event} ${action} (delivery: ${deliveryId})`);

    // 4. Route by Linear-Event header.
    switch (event) {
      case 'Issue':
        console.log(`Issue ${action}: ${payload.data?.title}`);
        // Your code: sync issue to external tracker, notify Slack, etc.
        break;

      case 'Comment':
        console.log(`Comment ${action} on issue ${payload.data?.issueId}`);
        // Your code: mirror discussion, bot replies, etc.
        break;

      case 'IssueLabel':
        console.log(`Label ${action}: ${payload.data?.name}`);
        // Your code: tag-based routing, analytics, etc.
        break;

      case 'Project':
        console.log(`Project ${action}: ${payload.data?.name}`);
        // Your code: roadmap dashboard sync, etc.
        break;

      case 'ProjectUpdate':
        console.log(`Project update ${action} on project ${payload.data?.projectId}`);
        // Your code: status report digests, etc.
        break;

      case 'Cycle':
        console.log(`Cycle ${action}: ${payload.data?.name ?? payload.data?.number}`);
        // Your code: sprint dashboards, burndown, etc.
        break;

      case 'Reaction':
        console.log(`Reaction ${action} (${payload.data?.emoji})`);
        // Your code: engagement analytics, etc.
        break;

      case 'IssueSLA':
        console.log(`SLA event on issue ${payload.issueData?.id}`);
        // Your code: escalation, paging, etc.
        break;

      case 'OAuthAppRevoked':
        console.log(`OAuth app revoked: ${payload.oauthClientId}`);
        // Your code: cleanup access tokens, etc.
        break;

      default:
        console.log(`Unhandled Linear event: ${event}`);
    }

    // 5. Acknowledge receipt.
    res.status(200).send('OK');
  }
);

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = { app, verifyLinearWebhook, isFreshTimestamp };

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/linear`);
  });
}
```

### Next.js

From [webhook-skills: skills/linear-webhooks/examples/nextjs/app/webhooks/linear/route.ts](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/linear-webhooks/examples/nextjs/app/webhooks/linear/route.ts)

```typescript
// Generated with: linear-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

// Linear's recommended replay-protection window for `webhookTimestamp`.
const WEBHOOK_TIMESTAMP_TOLERANCE_MS = 60 * 1000;

/**
 * Verify a Linear webhook signature.
 *
 * Linear sends a hex-encoded HMAC-SHA256 of the raw request body in the
 * `Linear-Signature` header — no `sha256=` prefix.
 */
export function verifyLinearWebhook(
  rawBody: string,
  signatureHeader: string | null,
  secret: string
): boolean {
  if (!signatureHeader || !secret) {
    return false;
  }

  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  try {
    return crypto.timingSafeEqual(
      Buffer.from(signatureHeader, 'hex'),
      Buffer.from(expectedSignature, 'hex')
    );
  } catch {
    return false;
  }
}

export function isFreshTimestamp(
  webhookTimestamp: unknown,
  now: number = Date.now()
): boolean {
  if (typeof webhookTimestamp !== 'number') {
    return false;
  }
  return Math.abs(now - webhookTimestamp) <= WEBHOOK_TIMESTAMP_TOLERANCE_MS;
}

export async function POST(request: NextRequest) {
  // Read the raw body — `request.json()` would parse, breaking signature
  // verification because of whitespace/key-ordering normalisation.
  const body = await request.text();
  const signature = request.headers.get('linear-signature');
  const event = request.headers.get('linear-event');
  const deliveryId = request.headers.get('linear-delivery');

  if (!verifyLinearWebhook(body, signature, process.env.LINEAR_WEBHOOK_SECRET ?? '')) {
    console.error('Linear webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let payload: Record<string, unknown>;
  try {
    payload = JSON.parse(body);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  if (!isFreshTimestamp(payload.webhookTimestamp)) {
    console.error('Linear webhook timestamp is outside the 1 minute window');
    return NextResponse.json({ error: 'Stale webhook' }, { status: 400 });
  }

  const action = payload.action as string | undefined;
  const data = payload.data as Record<string, unknown> | undefined;

  console.log(`Received Linear ${event} ${action} (delivery: ${deliveryId})`);

  switch (event) {
    case 'Issue':
      console.log(`Issue ${action}: ${data?.title ?? ''}`);
      break;
    case 'Comment':
      console.log(`Comment ${action} on issue ${data?.issueId ?? ''}`);
      break;
    case 'IssueLabel':
      console.log(`Label ${action}: ${data?.name ?? ''}`);
      break;
    case 'Project':
      console.log(`Project ${action}: ${data?.name ?? ''}`);
      break;
    case 'ProjectUpdate':
      console.log(`Project update ${action} on project ${data?.projectId ?? ''}`);
      break;
    case 'Cycle':
      console.log(`Cycle ${action}: ${data?.name ?? data?.number ?? ''}`);
      break;
    case 'Reaction':
      console.log(`Reaction ${action} (${data?.emoji ?? ''})`);
      break;
    case 'IssueSLA':
      console.log(
        `SLA event on issue ${(payload.issueData as { id?: string } | undefined)?.id ?? ''}`
      );
      break;
    case 'OAuthAppRevoked':
      console.log(`OAuth app revoked: ${payload.oauthClientId ?? ''}`);
      break;
    default:
      console.log(`Unhandled Linear event: ${event}`);
  }

  return NextResponse.json({ received: true });
}
```

### FastAPI

From [webhook-skills: skills/linear-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/linear-webhooks/examples/fastapi/main.py)

```python
# Generated with: linear-webhooks skill
# https://github.com/hookdeck/webhook-skills

import hashlib
import hmac
import json
import os
import time

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

# Linear's recommended replay-protection window for `webhookTimestamp`.
WEBHOOK_TIMESTAMP_TOLERANCE_MS = 60 * 1000


def _get_secret() -> str:
    """Read the signing secret each request so tests can override the env var."""
    return os.environ.get("LINEAR_WEBHOOK_SECRET", "")


def verify_linear_webhook(raw_body: bytes, signature_header: str | None, secret: str) -> bool:
    """Verify a Linear webhook signature.

    Linear signs every webhook using HMAC-SHA256 over the raw request body and
    sends the hex-encoded digest in the ``Linear-Signature`` header. The
    header value is a bare hex string — Linear does **not** prefix it with
    ``sha256=``.
    """
    if not signature_header or not secret:
        return False

    expected_signature = hmac.new(
        secret.encode("utf-8"),
        raw_body,
        hashlib.sha256,
    ).hexdigest()

    return hmac.compare_digest(signature_header, expected_signature)


def is_fresh_timestamp(webhook_timestamp_ms, now_ms: int | None = None) -> bool:
    """Return True if ``webhook_timestamp_ms`` is within 1 minute of now.

    Linear's ``webhookTimestamp`` field is UNIX **milliseconds** since epoch.
    """
    if not isinstance(webhook_timestamp_ms, int) or isinstance(webhook_timestamp_ms, bool):
        return False
    if now_ms is None:
        now_ms = int(time.time() * 1000)
    return abs(now_ms - webhook_timestamp_ms) <= WEBHOOK_TIMESTAMP_TOLERANCE_MS


@app.post("/webhooks/linear")
async def linear_webhook(request: Request):
    # Read the raw body — `await request.json()` would parse the body, which
    # changes the byte representation and breaks signature verification.
    raw_body = await request.body()
    signature_header = request.headers.get("linear-signature")
    event = request.headers.get("linear-event")
    delivery_id = request.headers.get("linear-delivery")

    # 1. Verify the signature.
    if not verify_linear_webhook(raw_body, signature_header, _get_secret()):
        raise HTTPException(status_code=400, detail="Invalid signature")

    # 2. Parse the payload only after verifying.
    try:
        payload = json.loads(raw_body)
    except json.JSONDecodeError as exc:
        raise HTTPException(status_code=400, detail="Invalid JSON") from exc

    # 3. Reject stale deliveries.
    if not is_fresh_timestamp(payload.get("webhookTimestamp")):
        raise HTTPException(status_code=400, detail="Stale webhook")

    action = payload.get("action")
    print(f"Received Linear {event} {action} (delivery: {delivery_id})")

    data = payload.get("data") or {}

    # 4. Route by Linear-Event header.
    if event == "Issue":
        print(f"Issue {action}: {data.get('title')}")
        # Your code: sync to external tracker, notify Slack, etc.

    elif event == "Comment":
        print(f"Comment {action} on issue {data.get('issueId')}")
        # Your code: mirror discussion, bot replies, etc.

    elif event == "IssueLabel":
        print(f"Label {action}: {data.get('name')}")
        # Your code: tag-based routing, analytics, etc.

    elif event == "Project":
        print(f"Project {action}: {data.get('name')}")
        # Your code: roadmap dashboard sync, etc.

    elif event == "ProjectUpdate":
        print(f"Project update {action} on project {data.get('projectId')}")

    elif event == "Cycle":
        print(f"Cycle {action}: {data.get('name') or data.get('number')}")

    elif event == "Reaction":
        print(f"Reaction {action} ({data.get('emoji')})")

    elif event == "IssueSLA":
        issue_data = payload.get("issueData") or {}
        print(f"SLA event on issue {issue_data.get('id')}")

    elif event == "OAuthAppRevoked":
        print(f"OAuth app revoked: {payload.get('oauthClientId')}")

    else:
        print(f"Unhandled Linear event: {event}")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=3000)
```

Or install the Linear webhooks skill: `npx skills add hookdeck/webhook-skills --skill linear-webhooks`

## Common failures

- **Body parsed before verification.** Linear signs the exact raw body, so a re-stringified JSON body can produce a different signature. Capture the raw bytes before any body parser runs.
- **Looking for a prefix or base64.** `Linear-Signature` is plain hex with no `sha256=` prefix. Code copied from a GitHub handler that strips a prefix, or that decodes base64, never matches.
- **Replay check in the wrong unit or place.** `webhookTimestamp` is in milliseconds, so comparing it with a clock in seconds rejects everything. Check it when the request arrives: in a worker behind a queue, a real delivery can already be over a minute old.
- **Secret just rotated.** Rotation invalidates the old secret immediately, with no overlap, so deliveries fail until your handler has the new one.

From [Hookdeck's Linear guide](https://hookdeck.com/webhooks/linear/guide-duplicates-ordering-retries-timeouts).

---

Not affiliated with Linear. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/linear.json) · [Report a correction](https://hookdeck.com/contact)
