This event is triggered whenever a user adds a new connection. The registered handler runs before the connection is saved, meaning that if the handler throws an error, the connection will not be created. You can use handler to validate the connection and ensure that any necessary setup code has run successfully.

Example

Here’s an example that creates a webhook handler.

TypeScript
// src/events/connection-added.event.ts
import {createWebhookHandler, updateWebhookHandler} from "attio/server"
import type {Connection} from "attio/server"

export default async function connectionAdded({connection}: {connection: Connection}) {
    // You can create multiple webhook handlers for the same file
    const webhookHandler = await createWebhookHandler({
        fileName: "acme-webhook",
    })

    // create Webhook in third party system, with webhook handler URL
    const acmeResponse = await fetch(`https://api.acmeinc.com/api/v1/registerWebhook`, {
        method: "POST",
        headers: {
            "Content-Type": "application/vnd.api+json",
            "Authorization": `Bearer ${connection.value}`,
        },
        body: JSON.stringify({
            name: "prospect-enrolled",
            url: webhookHandler.url,
        }),
    })

    if (!acmeResponse.ok) {
        throw new Error("Failed to register webhook")
    }

    const body = await acmeResponse.json()

    // We store the external webhook ID in Attio so we can clean it later
    await updateWebhookHandler(webhookHandler.id, {
        externalWebhookId: body.webhookId,
    })
}

When the event handler is invoked the new connection is only available as argument. It will not be available from usual Server SDK Connection functions (getUserConnection() / getWorkspaceConnection()).