Updated on November 24, 2026
To use the WhatsApp Business API with NestJS, build a WhatsappModule with three pieces: a controller that verifies the webhook and validates the X-Hub-Signature-256 signature against the raw body (enabled with rawBody: true in NestFactory.create), a service that sends the POST to the /messages endpoint, and a BullMQ queue that processes events and outgoing messages with retry. Two details break most integrations: Nest’s POST handlers return 201 by default, and the signature won’t match if you compute it over the already-parsed JSON.
The WhatsApp bot with Node.js and Express walks through the basic flow in plain JavaScript. Here the goal is to fit the same logic into Nest’s structure: modules, dependency injection, queues and tests.
Module structure
npm install --save @nestjs/bullmq bullmq ioredis
src/
main.ts
app.module.ts
whatsapp/
whatsapp.module.ts
whatsapp.controller.ts
whatsapp.service.ts
whatsapp.processor.ts
signature.ts
| File | Responsibility |
|---|---|
main.ts | Create the application with rawBody: true |
whatsapp.controller.ts | Verification GET and webhook POST |
signature.ts | Validate the HMAC-SHA256 in constant time |
whatsapp.service.ts | Send text and template messages to the API |
whatsapp.processor.ts | Consume the queue: process events and send replies |
main.ts: enabling the raw body
The webhook signature is an HMAC-SHA256 of the exact body Meta sent, according to Meta’s webhook endpoint page. Nest’s body parser turns that body into an object, and re-serializing it with JSON.stringify does not give you back the same bytes. The NestJS raw body page solves this with a single option:
// src/main.ts
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
The documentation warns that this only works with the global body parser enabled, so don’t pass bodyParser: false. With rawBody: true, req.rawBody is available as a Buffer and @Body() keeps working normally on every other route.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
app.module.ts and whatsapp.module.ts
// src/app.module.ts
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { WhatsappModule } from './whatsapp/whatsapp.module';
@Module({
imports: [
BullModule.forRoot({
connection: {
host: process.env.REDIS_HOST ?? 'localhost',
port: Number(process.env.REDIS_PORT ?? 6379),
},
}),
WhatsappModule,
],
})
export class AppModule {}
// src/whatsapp/whatsapp.module.ts
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { WhatsappController } from './whatsapp.controller';
import { WhatsappService } from './whatsapp.service';
import { WhatsappProcessor } from './whatsapp.processor';
@Module({
imports: [BullModule.registerQueue({ name: 'whatsapp' })],
controllers: [WhatsappController],
providers: [WhatsappService, WhatsappProcessor],
exports: [WhatsappService],
})
export class WhatsappModule {}
forRoot and registerQueue follow the NestJS queues page. Exporting WhatsappService lets other modules (orders, billing) send messages without knowing the API details.
Signature validation
// src/whatsapp/signature.ts
import { createHmac, timingSafeEqual } from 'node:crypto';
export function isValidSignature(
raw: Buffer | undefined,
header: string | undefined,
secret: string,
): boolean {
if (!raw || !header) return false;
const expected = Buffer.from(
'sha256=' + createHmac('sha256', secret).update(raw).digest('hex'),
);
const received = Buffer.from(header);
return expected.length === received.length && timingSafeEqual(expected, received);
}
Node’s timingSafeEqual throws when the buffers have different lengths, which is why the length check comes first. Keeping the function in its own file makes it easy to unit test. The same algorithm in other languages is covered in how to validate the webhook signature.
The controller
// src/whatsapp/whatsapp.controller.ts
import {
Controller,
Get,
Header,
Headers,
HttpCode,
Post,
Query,
Req,
ForbiddenException,
UnauthorizedException,
type RawBodyRequest,
} from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import type { Request } from 'express';
import { isValidSignature } from './signature';
@Controller('whatsapp')
export class WhatsappController {
constructor(@InjectQueue('whatsapp') private readonly queue: Queue) {}
@Get('webhook')
@Header('Content-Type', 'text/plain')
verify(@Query() query: Record<string, string>): string {
if (
query['hub.mode'] === 'subscribe' &&
query['hub.verify_token'] === process.env.WA_VERIFY_TOKEN
) {
return query['hub.challenge'] ?? '';
}
throw new ForbiddenException();
}
@Post('webhook')
@HttpCode(200)
async receive(
@Req() req: RawBodyRequest<Request>,
@Headers('x-hub-signature-256') signature: string | undefined,
): Promise<{ ok: true }> {
if (!isValidSignature(req.rawBody, signature, process.env.META_APP_SECRET ?? '')) {
throw new UnauthorizedException();
}
await this.queue.add('inbound', req.body, {
attempts: 5,
backoff: { type: 'exponential', delay: 1000 },
removeOnComplete: 1000,
});
return { ok: true };
}
}
The points that generate the most support tickets:
@HttpCode(200). The NestJS controllers documentation says the default status is200, except forPOST, which returns201. Meta expects200, so make it explicit.- The whole
@Query()object. The verification parameters have dots in their names (hub.mode,hub.verify_token,hub.challenge). Reading the whole object and accessingquery['hub.mode']avoids surprises with the query string parser. @Header('Content-Type', 'text/plain'). The challenge must be returned as-is, without JSON quotes.- No heavy logic in the handler. The controller only validates and enqueues. Calling an AI model, a CRM or the WhatsApp API itself before responding delays the
200and triggers redeliveries.
req.body is still available because the JSON parser stays active. If you’d rather process exactly the signed bytes, enqueue req.rawBody.toString('utf8') and run JSON.parse in the worker.
The sending service
// src/whatsapp/whatsapp.service.ts
import { Injectable, Logger } from '@nestjs/common';
const RETRYABLE = new Set([130429, 131000, 131016, 131056]);
export class WhatsappApiError extends Error {
constructor(
message: string,
readonly code: number | undefined,
readonly retryable: boolean,
) {
super(message);
}
}
@Injectable()
export class WhatsappService {
private readonly logger = new Logger(WhatsappService.name);
private readonly url = process.env.WA_SEND_URL ?? '';
private readonly token = process.env.WA_TOKEN ?? '';
sendText(to: string, body: string): Promise<string> {
return this.send({ to, type: 'text', text: { body } });
}
sendTemplate(to: string, name: string, lang: string, params: string[]): Promise<string> {
return this.send({
to,
type: 'template',
template: {
name,
language: { code: lang },
components: [
{ type: 'body', parameters: params.map((text) => ({ type: 'text', text })) },
],
},
});
}
private async send(message: Record<string, unknown>): Promise<string> {
const res = await fetch(this.url, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ messaging_product: 'whatsapp', ...message }),
signal: AbortSignal.timeout(15_000),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const code: number | undefined = data?.error?.code;
const retryable = res.status >= 500 || (code !== undefined && RETRYABLE.has(code));
this.logger.warn(`Send failed: ${code} ${data?.error?.message}`);
throw new WhatsappApiError(data?.error?.message ?? res.statusText, code, retryable);
}
return data.messages[0].id as string;
}
}
The service uses Node.js’s native fetch, with no extra dependency. The URL comes from WA_SEND_URL: on the WhatsApp Cloud API directly, that’s https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages, per Meta’s send messages page. A successful response includes the wamid in messages[0].id, but that only means Meta accepted the request; delivery is confirmed later, through the statuses in the webhook.
The codes in RETRYABLE come from Meta’s error code list: 130429 (throughput limit), 131056 (too many messages to the same contact in a short time), 131016 (service unavailable) and 131000 (unknown error). Errors such as 131047 (outside the 24-hour window), 132000 (parameters don’t match the template) and 190 (expired token) don’t get better with a retry. See the annotated list in WhatsApp API error codes.
The queue processor
// src/whatsapp/whatsapp.processor.ts
import { InjectQueue, Processor, WorkerHost } from '@nestjs/bullmq';
import { Job, Queue, UnrecoverableError } from 'bullmq';
import { WhatsappApiError, WhatsappService } from './whatsapp.service';
type SendJob = { to: string; body: string };
@Processor('whatsapp')
export class WhatsappProcessor extends WorkerHost {
constructor(
private readonly wa: WhatsappService,
@InjectQueue('whatsapp') private readonly queue: Queue,
) {
super();
}
async process(job: Job): Promise<unknown> {
if (job.name === 'inbound') return this.handleInbound(job.data);
if (job.name === 'send-text') return this.handleSend(job.data as SendJob);
return undefined;
}
private async handleInbound(payload: any): Promise<void> {
for (const entry of payload?.entry ?? []) {
for (const change of entry.changes ?? []) {
const value = change.value ?? {};
for (const msg of value.messages ?? []) {
if (!(await markAsSeen(msg.id))) continue; // duplicate
if (msg.type === 'text') {
await this.queue.add(
'send-text',
{ to: msg.from, body: 'We got your message. We will reply shortly.' },
{ jobId: `reply-${msg.id}`, attempts: 5, backoff: { type: 'exponential', delay: 2000 } },
);
}
}
for (const st of value.statuses ?? []) {
await saveStatus(st.id, st.status, st.errors?.[0]?.code);
}
}
}
}
private async handleSend(data: SendJob): Promise<string> {
try {
return await this.wa.sendText(data.to, data.body);
} catch (err) {
if (err instanceof WhatsappApiError && !err.retryable) {
throw new UnrecoverableError(err.message);
}
throw err;
}
}
}
// Implement with Redis (SET NX) or a unique index in the database.
declare function markAsSeen(wamid: string): Promise<boolean>;
declare function saveStatus(wamid: string, status: string, code?: number): Promise<void>;
According to the NestJS queues page, the consumer is a class decorated with @Processor('queue-name') that extends WorkerHost and implements process(), registered as a provider in the module. The attempts and backoff (fixed or exponential) options come from BullMQ: without attempts the job is not retried, and without backoff it is retried immediately, according to the BullMQ retry documentation.
Two things to watch:
jobIdhelps, but it doesn’t replace deduplication in the database. BullMQ ignores a job with a repeatedjobId, but the Job IDs documentation warns that jobs already removed (byremoveOnComplete, for example) don’t count as duplicates. That’s whymarkAsSeenstores thewamidin Redis or in the database under a unique key. The full topic is covered in duplicate webhooks and idempotency.- Permanent errors should not be retried. BullMQ’s
UnrecoverableErrormoves the job to the failed set without further attempts, ignoringattempts, according to the BullMQ documentation. Use it for131047,132000,190and similar errors.
To control the sending pace in large campaigns, the BullMQ worker accepts the limiter option (max jobs every duration milliseconds), which applies to the whole queue, even with multiple workers, according to the BullMQ rate limiting documentation. The complete architecture is in WhatsApp API sending queue with Redis and BullMQ.
Sending from another module
With WhatsappService exported, any module that imports WhatsappModule can send templates:
// src/orders/orders.service.ts
import { Injectable } from '@nestjs/common';
import { WhatsappService } from '../whatsapp/whatsapp.service';
@Injectable()
export class OrdersService {
constructor(private readonly wa: WhatsappService) {}
async confirm(order: { phone: string; customer: string; number: string }) {
// save the order first; only then notify the customer
return this.wa.sendTemplate(order.phone, 'confirmacao_pedido', 'pt_BR', [
order.customer,
order.number,
]);
}
}
Outside the 24-hour window, only approved templates can be sent. In production, put this send on the queue as well, so you get retries without blocking the request that created the order.
Testing the controller
A unit test for the signature needs neither Nest nor the network:
// src/whatsapp/signature.spec.ts
import { createHmac } from 'node:crypto';
import { isValidSignature } from './signature';
const secret = 'test-secret';
const body = Buffer.from('{"object":"whatsapp_business_account","entry":[]}');
const sign = (b: Buffer) => 'sha256=' + createHmac('sha256', secret).update(b).digest('hex');
describe('isValidSignature', () => {
it('accepts a correct signature', () => {
expect(isValidSignature(body, sign(body), secret)).toBe(true);
});
it('rejects a modified body', () => {
const altered = Buffer.from(body.toString().replace('[]', '[{}]'));
expect(isValidSignature(altered, sign(body), secret)).toBe(false);
});
it('rejects a missing header or one with a different length', () => {
expect(isValidSignature(body, undefined, secret)).toBe(false);
expect(isValidSignature(body, 'sha256=abc', secret)).toBe(false);
});
});
For end-to-end tests, NestJS integrates with Supertest through Test.createTestingModule and createNestApplication, as shown in the NestJS testing documentation. Payload fixtures, flow tests and using Meta’s test number are covered in how to test a WhatsApp bot.
How to do this with Vectalk
Vectalk is a proxy for the official WhatsApp Cloud API with the same payloads, so the module doesn’t change. Just adjust the variables:
WA_SEND_URL=https://apis.vectalk.com.br/api/messagesandWA_TOKENset to the token created under Settings → API Tokens (Configurações → API Tokens), as in the quickstart guide.- With an instance token, the
phone_number_idis resolved automatically; with an organization token, includephone_number_idin the body, per the authentication page. Media uploads and templates require an instance token. - Register the controller URL with
POST https://apis.vectalk.com.br/api/webhooks(instance_id,url,name). The Hub forwards the same payload Meta sends and expects a200within 20 seconds, according to the Vectalk webhooks documentation.
Vectalk’s documentation does not describe a signature header on forwarded requests. Protect the route with your own secret in the registered URL (for example, ?key=... validated in a guard) and confirm with the team through the contact page. To get started, create your account. For the big picture, see the official WhatsApp API guide; the same integration in Python is in WhatsApp API with Django.
Frequently asked questions
Why doesn’t the signature match even with the correct app secret?
Almost always because the hash is being computed over JSON.stringify(req.body) instead of req.rawBody. Make sure rawBody: true is set in NestFactory.create and that no custom middleware has disabled the body parser.
Does it work with Fastify instead of Express?
Yes. The NestJS raw body page shows the same option with FastifyAdapter, typing the request as RawBodyRequest<FastifyRequest>.
Do I need Redis to get started?
For a prototype, you can call the service directly from the controller after responding, but you lose retries and reprocessing. In production, use the queue: BullMQ persists jobs in Redis and resumes pending ones when the application restarts.
How do I keep the same customer from getting a duplicate reply?
Deduplicate by the wamid of the incoming message using shared storage (Redis with SET NX or a unique index in the database). Local memory won’t work when you run more than one instance.
Where can I see the fields for each message type and status?
In webhook payload examples and in message status via webhook.
Official sources consulted on November 24, 2026: Meta: send messages, Meta: create a webhook endpoint, Meta: error codes, NestJS: raw body, NestJS: controllers, NestJS: queues, NestJS: testing, BullMQ: retrying jobs, BullMQ: Job IDs, BullMQ: rate limiting, BullMQ: stop retrying jobs, Vectalk: quickstart, Vectalk: authentication, Vectalk: webhooks.
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
