Skip to content

Open-source status page, incident response and uptime monitoring

chore: webhook notifications add headers (#2025)

Maximilian Kaskeb0ef912df5e7
diff --git a/apps/dashboard/src/components/forms/notifications/form-webhook.tsx b/apps/dashboard/src/components/forms/notifications/form-webhook.tsx
index 4e2d75095..a19fa6ca1 100644
--- a/apps/dashboard/src/components/forms/notifications/form-webhook.tsx
+++ b/apps/dashboard/src/components/forms/notifications/form-webhook.tsx
@@ -25,19 +25,28 @@ import { Label } from "@openstatus/ui/components/ui/label";
import { cn } from "@openstatus/ui/lib/utils";
import { useMutation } from "@tanstack/react-query";
import { isTRPCClientError } from "@trpc/client";
+import { Plus, X } from "lucide-react";
import React, { useTransition } from "react";
-import { useForm } from "react-hook-form";
+import { useFieldArray, useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
const schema = z.object({
name: z.string(),
provider: z.literal("webhook"),
- data: z.record(z.string(), z.string()),
+ data: z.object({
+ endpoint: z.string().url(),
+ headers: z.array(
+ z.object({
+ key: z.string().min(1, "Key is required"),
+ value: z.string(),
+ }),
+ ),
+ }),
monitors: z.array(z.number()),
});
-type FormValues = z.infer<typeof schema>;
+type FormValues = z.input<typeof schema>;
export function FormWebhook({
defaultValues,
@@ -57,11 +66,15 @@ export function FormWebhook({
provider: "webhook",
data: {
endpoint: "",
- // headers: []
+ headers: [],
},
monitors: [],
},
});
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: "data.headers",
+ });
const [isPending, startTransition] = useTransition();
const { setIsDirty } = useFormSheetDirty();
const trpc = useTRPC();
@@ -105,10 +118,11 @@ export function FormWebhook({
try {
const provider = form.getValues("provider");
const endpoint = form.getValues("data.endpoint");
+ const headers = form.getValues("data.headers");
const promise = sendTestMutation.mutateAsync({
provider,
data: {
- webhook: { endpoint },
+ webhook: { endpoint, headers },
},
});
toast.promise(promise, {
@@ -176,6 +190,60 @@ export function FormWebhook({
</FormItem>
)}
/>
+ <FormItem>
+ <FormLabel>Request Headers</FormLabel>
+ <FormDescription>
+ Custom headers to include in every webhook request.
+ </FormDescription>
+ {fields.map((field, index) => (
+ <div key={field.id} className="grid gap-2 sm:grid-cols-5">
+ <FormField
+ control={form.control}
+ name={`data.headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Key" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`data.headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="Value" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ aria-label="Remove header"
+ onClick={() => remove(index)}
+ >
+ <X />
+ </Button>
+ </div>
+ ))}
+ <div>
+ <Button
+ size="sm"
+ variant="outline"
+ type="button"
+ onClick={() => append({ key: "", value: "" })}
+ >
+ <Plus />
+ Add Header
+ </Button>
+ </div>
+ <FormMessage />
+ </FormItem>
<div>
<Button
variant="outline"
diff --git a/apps/dashboard/src/components/forms/notifications/form.tsx b/apps/dashboard/src/components/forms/notifications/form.tsx
index 9a675c0e3..651a6ee0e 100644
--- a/apps/dashboard/src/components/forms/notifications/form.tsx
+++ b/apps/dashboard/src/components/forms/notifications/form.tsx
@@ -36,7 +36,7 @@ const schema = z.object({
"google-chat",
"grafana-oncall",
]),
- data: z.record(z.string(), z.string()).or(z.string()),
+ data: z.record(z.string(), z.any()).or(z.string()),
monitors: z.array(z.number()),
});
diff --git a/packages/api/src/router/notification.ts b/packages/api/src/router/notification.ts
index 0381f8f86..6e7364a2e 100644
--- a/packages/api/src/router/notification.ts
+++ b/packages/api/src/router/notification.ts
@@ -81,7 +81,18 @@ export const notificationRouter = createTRPCRouter({
name: z.string(),
data: z.partialRecord(
z.enum(notificationProvider),
- z.string().or(z.record(z.string(), z.string())),
+ z
+ .string()
+ .or(
+ z.record(
+ z.string(),
+ z
+ .string()
+ .or(
+ z.array(z.object({ key: z.string(), value: z.string() })),
+ ),
+ ),
+ ),
),
monitors: z.array(z.number()),
}),
@@ -163,7 +174,14 @@ export const notificationRouter = createTRPCRouter({
provider: z.enum(notificationProvider),
data: z.partialRecord(
z.enum(notificationProvider),
- z.record(z.string(), z.string()).or(z.string()),
+ z
+ .record(
+ z.string(),
+ z
+ .string()
+ .or(z.array(z.object({ key: z.string(), value: z.string() }))),
+ )
+ .or(z.string()),
),
name: z.string(),
monitors: z.array(z.number()).prefault([]),
@@ -284,7 +302,14 @@ export const notificationRouter = createTRPCRouter({
provider: z.enum(notificationProvider),
data: z.partialRecord(
z.enum(notificationProvider),
- z.record(z.string(), z.string()).or(z.string()),
+ z
+ .record(
+ z.string(),
+ z
+ .string()
+ .or(z.array(z.object({ key: z.string(), value: z.string() }))),
+ )
+ .or(z.string()),
),
}),
)
diff --git a/packages/notifications/webhook/src/index.test.ts b/packages/notifications/webhook/src/index.test.ts
index ccb008c26..e55b423db 100644
--- a/packages/notifications/webhook/src/index.test.ts
+++ b/packages/notifications/webhook/src/index.test.ts
@@ -100,8 +100,8 @@ describe("Webhook sendTest", () => {
expect(result).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(1);
const callArgs = fetchMock.mock.calls[0];
- // Empty headers array should result in empty object after transformHeaders
- expect(callArgs[1].headers).toEqual({});
+ // Empty headers array should still include Content-Type
+ expect(callArgs[1].headers).toEqual({ "Content-Type": "application/json" });
});
test("should send test webhook with 500 status code", async () => {
diff --git a/packages/notifications/webhook/src/index.ts b/packages/notifications/webhook/src/index.ts
index d966be3aa..3a87fd821 100644
--- a/packages/notifications/webhook/src/index.ts
+++ b/packages/notifications/webhook/src/index.ts
@@ -24,11 +24,10 @@ export const sendAlert = async ({
const res = await fetch(notificationData.webhook.endpoint, {
method: "post",
body: JSON.stringify(body),
- headers: notificationData.webhook.headers
- ? transformHeaders(notificationData.webhook.headers)
- : {
- "Content-Type": "application/json",
- },
+ headers: {
+ "Content-Type": "application/json",
+ ...transformHeaders(notificationData.webhook.headers ?? []),
+ },
});
if (!res.ok) {
throw new Error(`Failed to send webhook notification: ${res.statusText}`);
@@ -57,11 +56,10 @@ export const sendRecovery = async ({
const res = await fetch(url, {
method: "post",
body: JSON.stringify(body),
- headers: notificationData.webhook.headers
- ? transformHeaders(notificationData.webhook.headers)
- : {
- "Content-Type": "application/json",
- },
+ headers: {
+ "Content-Type": "application/json",
+ ...transformHeaders(notificationData.webhook.headers ?? []),
+ },
});
if (!res.ok) {
throw new Error(`Failed to send webhook notification: ${res.statusText}`);
@@ -90,11 +88,10 @@ export const sendDegraded = async ({
const res = await fetch(notificationData.webhook.endpoint, {
method: "post",
body: JSON.stringify(body),
- headers: notificationData.webhook.headers
- ? transformHeaders(notificationData.webhook.headers)
- : {
- "Content-Type": "application/json",
- },
+ headers: {
+ "Content-Type": "application/json",
+ ...transformHeaders(notificationData.webhook.headers ?? []),
+ },
});
if (!res.ok) {
throw new Error(`Failed to send webhook notification: ${res.statusText}`);
@@ -123,11 +120,10 @@ export const sendTest = async ({
const response = await fetch(url, {
method: "post",
body: JSON.stringify(body),
- headers: headers
- ? transformHeaders(headers)
- : {
- "Content-Type": "application/json",
- },
+ headers: {
+ "Content-Type": "application/json",
+ ...transformHeaders(headers ?? []),
+ },
});
if (!response.ok) {
throw new Error("Failed to send test");