Skip to content

NestJS Integration ​

The @terminaldz/zrexpress-sdk/nestjs subpath provides a module, a webhook guard, and a param decorator. NestJS (@nestjs/common / @nestjs/core, >=10 <12) is an optional peer — install it only if you use this subpath.

Register the module ​

ts
import { Module } from '@nestjs/common';
import { ZrExpressModule } from '@terminaldz/zrexpress-sdk/nestjs';

@Module({
  imports: [
    ZrExpressModule.forRoot({
      apiKey: process.env.ZREXPRESS_API_KEY!,
      tenantId: process.env.ZREXPRESS_TENANT_ID!,
      webhook: { secret: process.env.ZREXPRESS_WEBHOOK_SECRET }, // enables the guard
    }),
  ],
})
export class AppModule {}

forRootAsync reads config from DI (e.g. ConfigService):

ts
ZrExpressModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (c: ConfigService) => ({
    apiKey: c.getOrThrow('ZREXPRESS_API_KEY'),
    tenantId: c.getOrThrow('ZREXPRESS_TENANT_ID'),
    webhook: { secret: c.get('ZREXPRESS_WEBHOOK_SECRET') },
  }),
});

The module is global by default (opt out with isGlobal: false) and provides ZrExpressClient.

Inject the client ​

ts
import { Injectable } from '@nestjs/common';
import { ZrExpressClient } from '@terminaldz/zrexpress-sdk/nestjs';

@Injectable()
export class OrdersService {
  constructor(private readonly zr: ZrExpressClient) {}

  getProfile() {
    return this.zr.users.getProfile();
  }
}

Receive webhooks ​

ZrExpressWebhookGuard verifies the Svix signature over the raw body and attaches the typed event; @ZrWebhookEvent() retrieves it. A bad signature is a 401.

ts
import { Controller, Post, HttpCode, UseGuards } from '@nestjs/common';
import {
  ZrExpressWebhookGuard,
  ZrWebhookEvent,
  type ParcelWebhookEvent,
} from '@terminaldz/zrexpress-sdk/nestjs';

@Controller('webhooks')
export class WebhookController {
  @Post('zr')
  @HttpCode(200)              // ack fast
  @UseGuards(ZrExpressWebhookGuard)
  handle(@ZrWebhookEvent() event: ParcelWebhookEvent) {
    // De-dupe by svix-id; order by event.occurredAt; process out of band.
    return { ok: true };
  }
}

Bootstrap with rawBody: true ​

The guard verifies over the raw request bytes, so the app must be created with rawBody: true — otherwise the JSON parser consumes the body first and verification fails with a clear error:

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

const app = await NestFactory.create(AppModule, { rawBody: true }); // REQUIRED
await app.listen(3000);

A full working app is in examples/nest-app, and the Playground is a larger NestJS app that wires all of this together and was verified live.

Released under the MIT License. Not affiliated with ZR Express.