---
title: TypeScript | Avara
description: Handle Viewer webhooks in TypeScript (Express).
---

Viewer only implements three webhooks. Read [What webhooks should I configure](/integration/viewer/what-webhooks-should-i-configure/index.md) first — it maps each integration profile to the endpoints you should set. Leave unused endpoints blank. Report delivery, patient/study enrichment, and clinical context enrichment are AutoScribe, not Viewer.

This page is the TypeScript (Express) implementation guide: verify signatures, then handle only the events you enabled.

## Webhook security

All webhook requests from Avara are signed using HMAC-SHA256 with Standard Webhooks headers (`webhook-id`, `webhook-timestamp`, `webhook-signature`). Copy the webhook secret from [API Config](/integration/viewer/api-config/index.md) (**View Webhook Secret**) and set it as the `AVARA_WEBHOOK_KEY` environment variable. The SDK’s `unwrap()` method reads that variable, verifies the signature, and returns a typed event. Every Avara→partner POST expects **HTTP 200** with a JSON body matching that event’s response schema. Synchronous hooks should respond within about **30 seconds**.

You can use `unsafeUnwrap()` instead of `unwrap()` to skip signature verification, but this is not recommended for production as it bypasses security checks.

```
import Avara from "avara";
import express, { Request, Response } from "express";


const client = new Avara(); // reads AVARA_WEBHOOK_KEY from env
const app = express();
app.use(express.json());


app.post("/webhooks/avara", async (req: Request, res: Response) => {
  const event = client.webhooks.unwrap(req.body, req.headers);


  if (event.type === "study.access_requested") {
    // Handle study access request
    const { studyId, studyInstanceUid } = event.data;
    // ...
  }


  if (event.type === "secondary_capture.access_requested") {
    // Handle secondary capture upload request
    const { studyId, studyInstanceUid } = event.data;
    // ...
  }


  if (event.type === "modality_worklist.requested") {
    // Handle modality worklist request
    const { clinicId, callingAe, dateStart, dateEnd } = event.data;
    // ...
  }
});
```

## Study Image Access

The `study.access_requested` webhook is sent when Avara needs presigned URLs for DICOM images (and optional non-DICOM media). This is a **synchronous (hard) webhook** — you must respond within about 30 seconds. This webhook is sent before a study can be viewed in the Avara interface.

When Avara needs to access study images, it sends a POST request to your webhook endpoint. Your endpoint must respond with presigned GET URLs. The SDK’s `unwrap()` method returns a typed `StudyAccessRequestedWebhookEvent` that you can use directly.

Return `authorized: false` with an `error` when the caller must not access the study. Returning `authorized: true` with an empty `urls` array (and omitted or empty `mediaUrls`) is treated as no data available, not as a denial.

```
import Avara from "avara";
import express, { Request, Response } from "express";


const client = new Avara();
const app = express();
app.use(express.json());


app.post("/webhooks/avara", async (req: Request, res: Response) => {
  const event = client.webhooks.unwrap(req.body, req.headers);


  if (event.type === "study.access_requested") {
    const { studyId, studyInstanceUid } = event.data;


    // This is your internal business logic
    const presignedUrls = await generatePresignedUrlsForStudy(studyInstanceUid);


    if (presignedUrls.length === 0) {
      return res.status(200).json({
        authorized: false,
        error: "Study not found in PACS",
      });
    }


    res.status(200).json({
      authorized: true,
      urls: presignedUrls,
    });
  }
});


// This is your internal business logic
async function generatePresignedUrlsForStudy(
  studyInstanceUid: string
): Promise<string[]> {
  // Query your PACS/RIS system for the study
  // Generate presigned URLs for each DICOM image
  // Return a flat list of all image URLs
  return [
    "https://storage.example.com/dicom/image1.dcm?token=abc123",
    "https://storage.example.com/dicom/image2.dcm?token=def456",
  ];
}
```

**Response Format**

```
interface StudyAccessRequestedWebhookResponse {
  authorized: boolean;
  urls: string[]; // Flat list of DICOM GET URLs (may be empty)
  mediaUrls?: Array<{ url: string; mimeType: string; fileName?: string }>;
  error?: string; // Error message if authorization failed
}
```

## Secondary Capture Upload

The `secondary_capture.access_requested` webhook is sent when a viewer user creates a secondary capture. This is a **synchronous (hard) webhook** — you must return presigned PUT URLs in-request, within about 30 seconds.

Avara asks for upload URLs before writing the generated DICOM to your storage. The SDK’s `unwrap()` method returns a typed `SecondaryCaptureAccessRequestedWebhookEvent`. Respond `authorized: false` with an `error` if the study cannot be written. `uploadUrls` must be PUT-capable; the client uploads with `Content-Type: application/dicom` and writes the same object to every URL. Series and SOP UIDs are provided when available so you can pre-compute object keys. If you send `contentCreatorName`, Avara ignores it and derives the creator name server-side.

```
import Avara from "avara";
import express, { Request, Response } from "express";


const client = new Avara();
const app = express();
app.use(express.json());


app.post("/webhooks/avara", async (req: Request, res: Response) => {
  const event = client.webhooks.unwrap(req.body, req.headers);


  if (event.type === "secondary_capture.access_requested") {
    const { studyId, studyInstanceUid, seriesInstanceUid, sopInstanceUid } =
      event.data;


    // This is your internal business logic
    const uploadUrls = await generateSecondaryCaptureUploadUrls({
      studyInstanceUid,
      seriesInstanceUid,
      sopInstanceUid,
    });


    if (uploadUrls.length === 0) {
      return res.status(200).json({
        authorized: false,
        error: "Study cannot be written",
      });
    }


    res.status(200).json({
      authorized: true,
      uploadUrls,
    });
  }
});


// This is your internal business logic
async function generateSecondaryCaptureUploadUrls(params: {
  studyInstanceUid: string;
  seriesInstanceUid?: string;
  sopInstanceUid?: string;
}): Promise<string[]> {
  // Generate presigned PUT URLs for the secondary capture DICOM
  return [
    "https://storage.example.com/dicom/sc/image.dcm?token=abc123",
  ];
}
```

**Response Format**

```
interface SecondaryCaptureAccessRequestedWebhookResponse {
  authorized: boolean;
  uploadUrls: string[]; // Presigned PUT URLs; the viewer uploads the same object to every URL
  contentCreatorName?: string; // Ignored if provided — Avara derives creator name server-side
  error?: string; // When authorized is false
}
```

## Modality Worklist

The `modality_worklist.requested` webhook is sent when an on-prem modality (via an Avara PACS box) issues a C-FIND MWL. This is a **synchronous (hard) webhook** — the C-FIND path waits on your response, which should return within about 30 seconds.

Avara forwards the query window to your endpoint. Only one active API key per organization may have the Modality Worklist Webhook Endpoint set. The SDK’s `unwrap()` method returns a typed `ModalityWorklistRequestedWebhookEvent`. Return `authorized: false` with an `error` to surface a worklist failure to the modality. `items` is required and may be empty when there are no scheduled exams.

Item field names are PascalCase DICOM-style (not camelCase). `StudyInstanceUID` is required from the partner RIS today — do not omit it. `PatientName`, `PatientID`, and `Modality` must be non-empty. `ScheduledProcedureStepSequence` must contain at least one step.

```
import Avara from "avara";
import express, { Request, Response } from "express";


const client = new Avara();
const app = express();
app.use(express.json());


app.post("/webhooks/avara", async (req: Request, res: Response) => {
  const event = client.webhooks.unwrap(req.body, req.headers);


  if (event.type === "modality_worklist.requested") {
    const { clinicId, callingAe, sourceIp, dateStart, dateEnd, modality } =
      event.data;


    // This is your internal business logic
    const items = await queryModalityWorklist({
      clinicId,
      callingAe,
      sourceIp,
      dateStart,
      dateEnd,
      modality,
    });


    res.status(200).json({
      authorized: true,
      items,
    });
  }
});


// This is your internal business logic
async function queryModalityWorklist(params: {
  clinicId: string;
  callingAe: string;
  sourceIp: string;
  dateStart: string;
  dateEnd: string;
  modality?: string;
}): Promise<ModalityWorklistItem[]> {
  return [
    {
      PatientName: "DOE^JANE",
      PatientID: "MRN12345",
      PatientBirthDate: "19800115",
      PatientSex: "F",
      PatientSize: "1.65",
      PatientWeight: "62",
      Modality: "CT",
      AccessionNumber: "ACC-1001",
      StudyInstanceUID: "1.2.840.113619.2.55.3.604688119.868.1234567890.123",
      RequestedProcedureDescription: "CT CHEST WO CONTRAST",
      StudyDescription: "CT CHEST WO CONTRAST",
      ProtocolName: "CHEST_WO",
      ScheduledProcedureStepSequence: [
        {
          ScheduledProcedureStepStartDate: "20260813",
          ScheduledProcedureStepStartTime: "090000",
          ScheduledProcedureStepID: "SPSID-1",
          Modality: "CT",
          ScheduledProcedureStepDescription: "CT CHEST WO CONTRAST",
        },
      ],
    },
  ];
}
```

**Response Format**

```
interface ModalityWorklistRequestedWebhookResponse {
  authorized: boolean;
  items: ModalityWorklistItem[]; // Required; may be empty if authorized and no scheduled exams
  error?: string;
}


interface ModalityWorklistItem {
  PatientName: string; // Required, non-empty
  PatientID: string; // Required, non-empty
  PatientBirthDate: string; // Required (may be empty string)
  PatientSex: string; // Required (may be empty string)
  PatientSize: string; // Required (may be empty string)
  PatientWeight: string; // Required (may be empty string)
  Modality: string; // Required, non-empty
  AccessionNumber: string; // Required (may be empty string)
  StudyInstanceUID: string; // Required valid DICOM UID
  RequestedProcedureDescription: string;
  StudyDescription: string;
  ProtocolName: string;
  ScheduledProcedureStepSequence: Array<{
    ScheduledProcedureStepStartDate: string; // Non-empty
    ScheduledProcedureStepStartTime: string; // Non-empty
    ScheduledProcedureStepID: string; // Non-empty
    Modality: string; // Non-empty
    ScheduledProcedureStepDescription: string;
  }>; // Min 1
}
```
