Skip to main content

Building a Didit Webhook Listener with Fastify & PostgreSQL

Learn how to build a robust and secure webhook listener for Didit's real-time identity verification notifications using Node.js, Fastify, and PostgreSQL.

Building a Didit Webhook Listener with Fastify & PostgreSQL

Contents

In this guide

Jump to the part you need.

Secure Webhook IntegrationImplementing HMAC-SHA256 signature verification is crucial for ensuring the authenticity and integrity of Didit webhook payloads, protecting your application from forged requests and maintaining data security.

Real-time Data ProcessingUtilize webhooks to receive instant notifications on identity verification session status changes, enabling your application to react immediately and automate user onboarding or risk management workflows.

Scalable Data StorageLeverage PostgreSQL to efficiently store and manage webhook data, allowing for robust querying, auditing, and integration with your existing user management systems, ensuring data persistence and reliability.

Didit's Modular AdvantageDidit’s modular identity platform and comprehensive webhook system simplify integration, providing developers with clean APIs and real-time data flows to build flexible, AI-native KYC solutions with Core KYC and no setup fees.

Understanding Didit Webhooks and Their Importance

In the world of identity verification, real-time feedback is paramount. Whether you're onboarding new users, preventing fraud, or ensuring compliance, knowing the status of a verification session as it happens is critical. This is where webhooks come in. Didit's webhooks provide an automated way to receive notifications about events occurring within your identity verification workflows, such as a session completing, failing, or requiring further action.

Instead of constantly polling the Didit API for updates, which can be inefficient and lead to delays, webhooks push data directly to your configured endpoint. This event-driven architecture ensures your application always has the most up-to-date information, allowing for immediate processing and a smoother user experience. For example, once a user successfully completes Didit's ID Verification and Passive & Active Liveness checks, a webhook can trigger the next step in your onboarding flow instantly.

Didit offers configurable webhook versions, with v3 being the recommended standard for its comprehensive payload structure. You can set your webhook URL, version, and even define data retention policies directly through the Didit Business Console or via the API, giving you full control over your data flow and compliance obligations.

Setting Up Your Fastify Webhook Listener

Fastify is a fast and low-overhead web framework for Node.js, making it an excellent choice for building performant webhook listeners. Here's how to get started:

1. Project Setup and Dependencies

First, initialize your Node.js project and install the necessary packages:

mkdir didit-webhook-listener
cd didit-webhook-listener
npm init -y
npm install fastify dotenv pg crypto

Create an .env file to store your Didit webhook secret key and PostgreSQL connection details:

DIDIT_WEBHOOK_SECRET=your_didit_webhook_secret_key
DATABASE_URL=postgresql://user:password@host:port/database

You can retrieve your DIDIT_WEBHOOK_SECRET from the Didit Business Console under App Settings or via the Didit API's GET /v3/webhook/ endpoint.

2. Fastify Server Configuration

Create an app.js file. Fastify needs the raw body for signature verification, so we'll configure it to not parse JSON automatically for our webhook route.

require('dotenv').config();
const fastify = require('fastify')({ logger: true });
const crypto = require('crypto');
const { Client } = require('pg');

const DIDIT_WEBHOOK_SECRET = process.env.DIDIT_WEBHOOK_SECRET;
const DATABASE_URL = process.env.DATABASE_URL;

const pgClient = new Client({ connectionString: DATABASE_URL });

// Register a content parser for 'application/json' that leaves the body raw for specific routes
fastify.addContentTypeParser('application/json', { parseAs: 'buffer' }, function (req, body, done) {
  if (req.raw.url === '/webhooks/didit') {
    done(null, body); // Leave raw for webhook endpoint
  } else {
    try {
      const json = JSON.parse(body.toString());
      done(null, json);
    } catch (error) {
      error.statusCode = 400;
      done(error, undefined);
    }
  }
});

fastify.post('/webhooks/didit', async (request, reply) => {
  const signature = request.headers['x-signature'];
  const timestamp = request.headers['x-timestamp'];
  const rawBody = request.body;

  if (!signature || !timestamp || !rawBody) {
    reply.code(400).send({ message: 'Missing signature, timestamp, or body' });
    return;
  }

  // 1. Verify HMAC-SHA256 signature
  const expectedSignature = crypto
    .createHmac('sha256', DIDIT_WEBHOOK_SECRET)
    .update(`${timestamp}.${rawBody.toString()}`)
    .digest('hex');

  if (expectedSignature !== signature) {
    reply.code(403).send({ message: 'Invalid signature' });
    return;
  }

  // 2. Validate timestamp (e.g., within 5 minutes to prevent replay attacks)
  const fiveMinutesAgo = Date.now() - (5 * 60 * 1000);
  if (parseInt(timestamp) < fiveMinutesAgo) {
    reply.code(403).send({ message: 'Timestamp too old' });
    return;
  }

  // 3. Parse JSON body after verification
  let payload;
  try {
    payload = JSON.parse(rawBody.toString());
  } catch (error) {
    reply.code(400).send({ message: 'Invalid JSON payload' });
    return;
  }

  fastify.log.info('Received Didit webhook:', payload);

  // 4. Process the webhook payload (e.g., store in DB, update user status)
  try {
    await pgClient.query(
      'INSERT INTO webhooks (event_id, event_type, payload, received_at) VALUES ($1, $2, $3, NOW())',
      [payload.id, payload.event, JSON.stringify(payload)]
    );
    // Example: Update user status based on payload.status
    // await pgClient.query(
    //   'UPDATE users SET verification_status = $1 WHERE didit_session_id = $2',
    //   [payload.status, payload.session_id]
    // );
    reply.code(200).send({ message: 'Webhook received and processed' });
  } catch (dbError) {
    fastify.log.error('Database error:', dbError);
    reply.code(500).send({ message: 'Internal server error' });
  }
});

const start = async () => {
  try {
    await pgClient.connect();
    fastify.log.info('Connected to PostgreSQL');
    await fastify.listen({ port: 3000, host: '0.0.0.0' });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

Storing Webhook Data in PostgreSQL

Persisting webhook data is crucial for auditing, debugging, and ensuring data integrity. PostgreSQL is a robust relational database ideal for this task.

1. Database Schema

First, create a table to store your webhook events. This schema provides a good starting point:

CREATE TABLE webhooks (
    id SERIAL PRIMARY KEY,
    event_id VARCHAR(255) UNIQUE NOT NULL, -- Didit's unique event ID
    event_type VARCHAR(255) NOT NULL,
    payload JSONB NOT NULL, -- Store the full JSON payload
    received_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

2. Integrating with Fastify

As shown in the app.js example, we integrate the pg client to connect to your PostgreSQL database and insert the incoming webhook payload. The payload JSONB NOT NULL column is perfect for storing the entire JSON object, allowing for flexible querying later without predefined schema changes for every new field Didit might introduce.

Remember to handle potential database errors gracefully. The example above includes a basic try-catch block for database operations.

Securing Your Webhook Endpoint

Security is paramount when dealing with sensitive identity verification data. Didit employs HMAC-SHA256 signatures to ensure that incoming webhooks are legitimate and untampered.

1. HMAC Signature Verification

Every Didit webhook request includes two crucial headers: X-Signature and X-Timestamp. The X-Signature header contains an HMAC-SHA256 signature generated using your unique webhook secret and the raw request body concatenated with the timestamp. Your listener must:

  1. Retrieve your DIDIT_WEBHOOK_SECRET.
  2. Extract the X-Signature and X-Timestamp headers.
  3. Reconstruct the signed payload: `${timestamp}.${rawBody}`.
  4. Generate your own HMAC-SHA256 signature using your secret and the reconstructed payload.
  5. Compare your generated signature with the X-Signature from the request. If they don't match, reject the request.

The provided Fastify example demonstrates this exact process, ensuring that only authentic Didit webhooks are processed.

2. Timestamp Validation

The X-Timestamp header is vital for preventing replay attacks. A replay attack occurs when an attacker intercepts a legitimate webhook and resends it later. By checking that the timestamp is recent (e.g., within 5 minutes of the current time), you can mitigate this risk. The Fastify code snippet includes a check to ensure the timestamp is not too old.

How Didit Helps

Didit's platform is designed to make integrating identity verification seamless and secure. Our modular architecture allows you to plug-and-play various identity checks, from ID Verification for robust document analysis to NFC Verification for high-security ePassport/eID checks, and AML Screening & Monitoring for compliance. The webhook system is a core component of this modularity, providing real-time updates that enable you to orchestrate complex KYC workflows without constant polling.

Didit's AI-native approach means our systems are constantly learning and adapting, providing superior accuracy and fraud detection. The clear API documentation and developer-first mentality, combined with features like Core KYC and no setup fees, make it easy to get started. Our webhooks provide structured identity data, allowing your application to react intelligently to verification outcomes and automate trust at scale, globally. Whether you need to verify age using Didit's Age Estimation or ensure a user is a live person with Passive & Active Liveness, Didit provides the tools and the real-time feedback necessary for a robust identity solution.

Ready to Get Started?

Ready to see Didit in action? Get a free demo today.

Start verifying identities for free with Didit's free tier.

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

Questions

Blog questions

Who writes the Didit blog?
The Didit team. Guides reviewed by Alberto Rosas, co-founder and CEO, carry his byline. The rest are published as Didit.
Which topics does the blog cover?
Eight topics: ID verification, business verification (KYB), AML, sanctions and compliance, fraud prevention, transaction monitoring and crypto, country guides, agents and developers, and product updates.
Is the blog available in my language?
Yes, in 15 languages: English, Spanish, French, German, Brazilian and European Portuguese, Catalan, Russian, Arabic, Chinese, Japanese, Hindi, Indonesian, Korean and Swahili. Not every post is translated, so each language shows the posts it has.
Where do I find product updates?
In the changelog at /changelog/ and under the Product updates topic.
Are these posts legal advice?
No. Regulation posts explain rules; your legal team decides how they apply.
How do I find posts on one topic?
Open one of the eight topics, or search the blog.
Are posts dated?
Yes. Every post shows when it was published and when it was last updated.
Do posts link to the docs?
Developer posts link to the matching page on docs.didit.me and to the API reference.
Is the blog the same as the docs?
No. The blog explains rules, markets and product changes for a general reader, while docs.didit.me holds the integration guides and the API reference. Developer posts link the matching docs page and the API reference they describe.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.