𝗛𝗮𝗻𝗱𝗹𝗲 𝗡𝘆𝗹𝗮𝘀 𝗪𝗲𝗯𝗵𝗼𝗼𝗸𝘀 𝗶𝗻 𝗡𝗲𝘅𝘁.𝗷𝘀

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:

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 }); }

𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗧𝗶𝗽𝘀

• 메시지 중복을 제거하세요. 웹훅은 최소 한 번(at-least-once) 전달됩니다. 동일한 메시지를 두 번 처리하지 않도록 데이터베이스 제약 조건이나 Redis를 사용하세요. • 잘린 페이로드를 처리하세요. 메시지가 1MB를 초과하면 본문이 삭제됩니다. 전체 내용을 가져오려면 항상 API를 통해 메시지를 다시 호출하세요. • 정제된 콘텐츠를 사용하세요. 지저분한 HTML 대신 마크다운을 가져오려면 message.created.cleaned를 사용하세요. 이는 LLM에 더 적합합니다.

웹훅 핸들러에서 중복 제거를 어떻게 처리하시나요? Redis를 사용하시나요, 아니면 데이터베이스 제약 조건을 사용하시나요?

출처: https://dev.to/qasim157/handle-messagecreated-webhooks-in-nextjs-4e80