𝗛𝗮𝗻𝗱𝗹𝗲 𝗡𝘆𝗹𝗮𝘀 𝗪𝗲𝗯𝗵𝗼𝗼𝗸𝘀 𝗶𝗻 𝗡𝗲𝘅𝘁.𝗷𝘀
An email hits your AI agent. You have 10 seconds to respond.
If you use Nylas Agent Accounts, a message.created webhook hits your server immediately. In Next.js, you handle this with one route file.
Here is how to build it correctly.
𝗧𝗵𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝗛𝗮𝗻𝗱𝘀𝗵𝗮𝗸𝗲
When you create a webhook, Nylas sends a GET request with a challenge parameter. You must return the exact value in the response body.
Do not use JSON. Do not add quotes. Use a bare response. If you fail this, the webhook fails.
Example GET handler:
export async function GET(req: NextRequest) { const challenge = req.nextUrl.searchParams.get("challenge"); return new Response(challenge ?? "", { status: 200 }); }
𝗧𝗵𝗲 𝗣𝗢𝗦𝗧 𝗡𝗼𝘁𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻
When a message arrives, Nylas sends a POST request. Follow these three rules to avoid errors:
- Acknowledge immediately. Return a 200 status before you run your heavy logic. If your LLM takes too long, the webhook will time out.
- Verify signatures. Use the X-Nylas-Signature header and your webhook secret. This prevents unauthorized users from triggering your agent.
- Use the raw body. To verify the HMAC signature, you need the raw text. Read the text first, verify it, then parse the JSON.
Example POST handler:
export async function POST(req: NextRequest) { const raw = await req.text(); const signature = req.headers.get("x-nylas-signature") ?? "";
const expected = crypto .createHmac("sha256", process.env.NYLAS_WEBHOOK_SECRET!) .update(raw, "utf8") .digest("hex");
const valid = signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
if (!valid) { return new Response("invalid signature", { status: 401 }); }
const payload = JSON.parse(raw); const { object } = payload.data;
processMessage(object.grant_id, object.id).catch(console.error);
return NextResponse.json({ ok: true }, { status: 200 }); }
𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗧𝗶𝗽𝘀
• پیغامات کی تکرار ختم کریں (Deduplicate messages)۔ Webhooks کم از کم ایک بار (at-least-once) پیغام پہنچاتے ہیں۔ اس بات کو یقینی بنانے کے لیے کہ آپ ایک ہی پیغام کو دو بار پراسیس نہ کریں، ڈیٹا بیس کنسٹرینٹ یا Redis کا استعمال کریں۔
• ادھورے (truncated) پے لوڈز کو ہینڈل کریں۔ اگر کوئی پیغام 1 MB سے زیادہ ہو، تو اس کا باڈی (body) حصہ نکال دیا جاتا ہے۔ مکمل مواد حاصل کرنے کے لیے ہمیشہ API کے ذریعے پیغام کو دوبارہ فیچ (re-fetch) کریں۔
• صاف شدہ (cleaned) مواد استعمال کریں۔ الجھے ہوئے HTML کے بجائے مارک ڈاؤن حاصل کرنے کے لیے message.created.cleaned کا استعمال کریں۔ یہ آپ کے LLM کے لیے بہتر کام کرتا ہے۔
آپ اپنے webhook ہینڈلرز میں ڈی ڈپلیکیشن (deduplication) کو کیسے ہینڈل کرتے ہیں؟ کیا آپ Redis یا ڈیٹا بیس کنسٹرینٹ کا استعمال کرتے ہیں؟
ماخذ: https://dev.to/qasim157/handle-messagecreated-webhooks-in-nextjs-4e80