From 4984639f231795acaacb11085b9eec6d2ba2a4d1 Mon Sep 17 00:00:00 2001 From: Owen Rees Date: Sun, 10 Sep 2023 20:23:42 +0200 Subject: [PATCH] webhook calls moved server-side --- app/api/send-discord-notification/route.ts | 34 ++++++++++++++++++++++ handlers/formHandlers.ts | 2 +- lib/discordWebhook.ts | 8 +---- 3 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 app/api/send-discord-notification/route.ts diff --git a/app/api/send-discord-notification/route.ts b/app/api/send-discord-notification/route.ts new file mode 100644 index 0000000..238b9e8 --- /dev/null +++ b/app/api/send-discord-notification/route.ts @@ -0,0 +1,34 @@ +import { NextRequest, NextResponse } from "next/server"; + +export async function POST(req: NextRequest) { + const webhookURL = process.env.DISCORD_WEBHOOK_URL; + const { embeds } = await req.json(); + + if (!webhookURL) { + return NextResponse.json( + { error: `Discord webhook URL not found` }, + { status: 404 }, + ); + } + + try { + const webhookBody = { + embeds: embeds, + }; + + const webhookInfo = await fetch(webhookURL, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(webhookBody), + }); + + return NextResponse.json( + { success: `Message delivered to ${webhookInfo}` }, + { status: 200 }, + ); + } catch (error) { + return NextResponse.json({ error: `Connection refused` }, { status: 404 }); + } +} diff --git a/handlers/formHandlers.ts b/handlers/formHandlers.ts index 030e6f0..15059f6 100644 --- a/handlers/formHandlers.ts +++ b/handlers/formHandlers.ts @@ -29,8 +29,8 @@ export const handleTournamentSubmit = async ( setIsSending(true); try { - await tournamentFormToDB(formRefs); // write to DB await discordWebhook(formRefs); // send Discord notification + await tournamentFormToDB(formRefs); // write to DB setIsSending(false); setResponseMessage({ isSuccessful: true, diff --git a/lib/discordWebhook.ts b/lib/discordWebhook.ts index 7b87f84..2eeceac 100644 --- a/lib/discordWebhook.ts +++ b/lib/discordWebhook.ts @@ -10,12 +10,6 @@ const discordWebhook = async ({ yourEmailRef, messageRef, }: TournamentFormProps) => { - const webhookURL = process.env.NEXT_PUBLIC_DISCORD_WEBHOOK; - - if (!webhookURL) { - throw new Error("Discord webhook URL is not defined"); - } - const webhookBody = { embeds: [ { @@ -36,7 +30,7 @@ const discordWebhook = async ({ ], }; - return await fetch(webhookURL, { + return await fetch("/api/send-discord-notification", { method: "POST", headers: { "Content-Type": "application/json",