Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add resend webhook api handler #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

118 changes: 115 additions & 3 deletions src/commands/add/misc/resend/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
// 2. Add component at components/emails/FirstEmailTemplate.tsx
// 3. Add route handler at app/api/email/route.ts
// 4. Add email utils
// 4. Add email index.ts
// 5. Add email index.ts
// 6. Add webhook handler at app/api/webhooks/resend/route.ts

import { formatFilePath, getFilePaths } from "../../../filePaths/index.js";

Expand Down Expand Up @@ -173,7 +174,7 @@ const generateApiRoute = () => {
const { resend } = getFilePaths();
return `import { EmailTemplate } from "${formatFilePath(
resend.firstEmailComponent,
{ prefix: "alias", removeExtension: true },
{ prefix: "alias", removeExtension: true }
)}";
import { resend } from "${formatFilePath(resend.libEmailIndex, {
prefix: "alias",
Expand Down Expand Up @@ -212,7 +213,7 @@ const generateEmailIndexTs = () => {
return `import { Resend } from "resend";
import { env } from "${formatFilePath(init.envMjs, {
prefix: "alias",
removeExtension: true,
removeExtension: false,
})}";

export const resend = new Resend(env.RESEND_API_KEY);
Expand All @@ -229,10 +230,121 @@ export const emailSchema = z.object({
`;
};

const generateWebhooksApiRoute = () => {
const {
shared: { init },
} = getFilePaths();
return `import { Webhook } from "svix";
import { headers } from "next/headers";
import { env } from "${formatFilePath(init.envMjs, {
prefix: "alias",
removeExtension: false,
})}";

const webhookSecret = env.RESEND_WEBHOOK_SECRET;

const resendEventTypes = [
"email.sent",
"email.delivered",
"email.delivery_delayed",
"email.complained",
"email.bounced",
"email.opened",
"email.clicked",
] as const;

type ResendEventType = (typeof resendEventTypes)[number];

type ResendBaseData = {
created_at: string;
email_id: string;
from: string;
to: string[];
subject: string;
};

type ResendClickData = ResendBaseData & {
click: {
ipAddress: string;
link: string;
timestamp: string;
userAgent: string;
};
};

export type ResendWebhook =
| {
type: Exclude<ResendEventType, "email.clicked">;
created_at: string;
data: ResendBaseData;
}
| {
type: "email.clicked";
created_at: string;
data: ResendClickData;
};


/**
* Validate this post request was sent by resend
*/
async function validateRequest(request: Request) {
const payloadString = await request.text();
const headerPayload = headers();

const svixHeaders = {
"svix-id": headerPayload.get("svix-id")!,
"svix-timestamp": headerPayload.get("svix-timestamp")!,
"svix-signature": headerPayload.get("svix-signature")!,
};

const wh = new Webhook(webhookSecret);
return wh.verify(payloadString, svixHeaders) as ResendWebhook;
}

export async function POST(request: Request) {
let event: ResendWebhook | null = null;

try {
event = await validateRequest(request);
} catch (err) {
console.error("Error validating resend webhook:");
const message = err instanceof Error ? err.message : err;
console.error(message);
return new Response("Resend Webhook Error: " + message, { status: 400 });
}

console.log(event);

switch (event.type) {
case "email.sent":
break;
case "email.delivered":
break;
case "email.delivery_delayed":
break;
case "email.complained":
break;
case "email.bounced":
break;
case "email.opened":
break;
case "email.clicked":
break;
default:
break;
}

return new Response(null, { status: 200 });
}
`;
};

export const resendGenerators = {
generateResendPage,
generateEmailTemplateComponent,
generateApiRoute,
generateEmailIndexTs,
generateEmailUtilsTs,
generateWebhooksApiRoute,
};
26 changes: 22 additions & 4 deletions src/commands/add/misc/resend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const addResend = async (packagesBeingInstalled: AvailablePackage[]) => {
generateEmailIndexTs,
generateApiRoute,
generateEmailTemplateComponent,
generateWebhooksApiRoute,
} = resendGenerators;

// 1. Add page at app/resend/page.tsx
Expand Down Expand Up @@ -73,12 +74,29 @@ export const addResend = async (packagesBeingInstalled: AvailablePackage[]) => {
generateEmailIndexTs()
);

// 6. Add items to .env
addToDotEnv([{ key: "RESEND_API_KEY", value: "" }], rootPath, true);
// 7. Install packages (resend)
// 6. Add webhook handler at app/api/webhooks/resend/route.ts
createFile(
formatFilePath(resend.resendWebhooksApiRoute, {
prefix: "rootPath",
removeExtension: false,
}),
generateWebhooksApiRoute()
);

// 7. Add items to .env
addToDotEnv(
[
{ key: "RESEND_API_KEY", value: "" },
{ key: "RESEND_WEBHOOK_SECRET", value: "whsec..." },
],
rootPath,
true
);

// 8. Install packages (resend)
await installPackages(
{
regular: `resend${orm === null ? " zod @t3-oss/env-nextjs" : ""}`,
regular: `resend${orm === null ? " zod @t3-oss/env-nextjs" : ""} svix`,
dev: "",
},
preferredPackageManager
Expand Down
2 changes: 2 additions & 0 deletions src/commands/filePaths/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export const paths: { t3: Paths; normal: Paths } = {
emailApiRoute: "app/api/email/route.ts",
libEmailIndex: "lib/email/index.ts",
firstEmailComponent: "components/emails/FirstEmail.tsx",
resendWebhooksApiRoute: "app/api/webhooks/resend/route.ts",
},
stripe: {
stripeIndex: "lib/stripe/index.ts",
Expand Down Expand Up @@ -159,6 +160,7 @@ export const paths: { t3: Paths; normal: Paths } = {
emailApiRoute: "app/api/email/route.ts",
libEmailIndex: "lib/email/index.ts",
firstEmailComponent: "components/emails/FirstEmail.tsx",
resendWebhooksApiRoute: "app/api/webhooks/resend/route.ts",
},
stripe: {
stripeIndex: "lib/stripe/index.ts",
Expand Down
1 change: 1 addition & 0 deletions src/commands/filePaths/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,5 +84,6 @@ export type Paths = {
emailApiRoute: string;
emailUtils: string;
libEmailIndex: string;
resendWebhooksApiRoute: string;
};
};