Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(www): add Notion database as form destination for /go pages (#45175)

Alan Daniel2c892acec498
diff --git a/apps/www/_go/lead-gen/example-lead-gen.tsx b/apps/www/_go/lead-gen/example-lead-gen.tsx
index a41ea042b64..81c1187744b 100644
--- a/apps/www/_go/lead-gen/example-lead-gen.tsx
+++ b/apps/www/_go/lead-gen/example-lead-gen.tsx
@@ -261,14 +261,23 @@ alter table posts enable row level security;`,
disclaimer:
'By submitting this form, I confirm that I have read and understood the [Privacy Policy](https://supabase.com/privacy).',
crm: {
- hubspot: {
- formGuid: 'b9abbf77-86ae-4fe7-9147-d15922bf58ca',
- fieldMap: {
- firstName: 'firstname',
- lastName: 'lastname',
+ // hubspot: {
+ // formGuid: 'b9abbf77-86ae-4fe7-9147-d15922bf58ca',
+ // fieldMap: {
+ // firstName: 'firstname',
+ // lastName: 'lastname',
+ // },
+ // consent:
+ // 'By submitting this form, I confirm that I have read and understood the Privacy Policy.',
+ // },
+ notion: {
+ database_id: '3525004b775f80419b2ac0245affad06',
+ columnMap: {
+ firstName: 'First Name',
+ lastName: 'Last Name',
+ email: 'Company Email',
+ interest: 'What are you interested in?',
},
- consent:
- 'By submitting this form, I confirm that I have read and understood the Privacy Policy.',
},
},
},
diff --git a/packages/marketing/src/crm/hubspot.ts b/packages/marketing/src/crm/hubspot.ts
index c34036dd789..c5f5619e9fa 100644
--- a/packages/marketing/src/crm/hubspot.ts
+++ b/packages/marketing/src/crm/hubspot.ts
@@ -71,8 +71,13 @@ export class HubSpotClient {
}
}
+ // portalId comes from env; formGuid is validated at the zod layer to a
+ // UUID-like shape, but encodeURIComponent keeps this safe even if the
+ // client is constructed from an untrusted source.
const response = await fetch(
- `https://api.hsforms.com/submissions/v3/integration/submit/${this.portalId}/${this.formGuid}`,
+ `https://api.hsforms.com/submissions/v3/integration/submit/${encodeURIComponent(
+ this.portalId
+ )}/${encodeURIComponent(this.formGuid)}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
diff --git a/packages/marketing/src/crm/index.ts b/packages/marketing/src/crm/index.ts
index ce5eb2573ae..dc0a92b6782 100644
--- a/packages/marketing/src/crm/index.ts
+++ b/packages/marketing/src/crm/index.ts
@@ -2,76 +2,59 @@ import 'server-only'
import { CustomerIOClient, type CustomerIOConfig } from './customerio'
import { HubSpotClient, type HubSpotConfig } from './hubspot'
+import { NotionClient, type NotionConfig } from './notion'
export type { CustomerIOConfig } from './customerio'
export type { HubSpotConfig } from './hubspot'
+export type { NotionConfig } from './notion'
export { CustomerIOClient } from './customerio'
export { HubSpotClient } from './hubspot'
+export { NotionClient } from './notion'
-// --- Provider config types ---
-
-interface HubSpotProviderConfig {
- hubspot: HubSpotConfig
- customerio?: never
-}
-
-interface CustomerIOProviderConfig {
- hubspot?: never
- customerio: CustomerIOConfig
+export interface CRMConfig {
+ hubspot?: HubSpotConfig
+ customerio?: CustomerIOConfig
+ notion?: NotionConfig
}
-interface BothProvidersConfig {
- hubspot: HubSpotConfig
- customerio: CustomerIOConfig
-}
-
-export type CRMConfig = HubSpotProviderConfig | CustomerIOProviderConfig | BothProvidersConfig
-
-// --- Event option types per provider ---
-
-interface HubSpotEventFields {
+export interface CRMEventOptions {
+ /** Email used as identifier */
+ email: string
/** Fields submitted to HubSpot form (key = HubSpot field name, value = field value) */
- hubspotFields: Record<string, string>
+ hubspotFields?: Record<string, string>
/** HubSpot form context */
context?: { pageUri?: string; pageName?: string }
/** Legal consent text for HubSpot */
consent?: string
-}
-
-interface CustomerIOEventFields {
/** Event name for Customer.io tracking */
- event: string
+ event?: string
/** Properties attached to the Customer.io event */
properties?: Record<string, unknown>
/** Profile attributes to set on the Customer.io contact */
customerioProfile?: Record<string, unknown>
+ /** Notion page creation — values are keyed by Notion database column name */
+ notion?: {
+ databaseId: string
+ properties: Record<string, unknown>
+ }
}
-type BaseEventOptions = {
- /** Email used as identifier */
- email: string
-}
-
-type SubmitEventFor<T extends CRMConfig> = BaseEventOptions &
- (T extends { hubspot: HubSpotConfig } ? HubSpotEventFields : Partial<HubSpotEventFields>) &
- (T extends { customerio: CustomerIOConfig }
- ? CustomerIOEventFields
- : Partial<CustomerIOEventFields>)
-
-export class CRMClient<T extends CRMConfig = CRMConfig> {
+export class CRMClient {
private hubspot: HubSpotClient | null
private customerio: CustomerIOClient | null
+ private notion: NotionClient | null
- constructor(config: T) {
+ constructor(config: CRMConfig) {
this.hubspot = config.hubspot ? new HubSpotClient(config.hubspot) : null
this.customerio = config.customerio ? new CustomerIOClient(config.customerio) : null
+ this.notion = config.notion ? new NotionClient(config.notion) : null
}
/**
* Submit an event to configured providers in parallel.
- * Required fields are determined by which providers were configured.
+ * Each provider is invoked only when both its client and its payload are present.
*/
- async submitEvent(options: SubmitEventFor<T>): Promise<{ errors: Error[] }> {
+ async submitEvent(options: CRMEventOptions): Promise<{ errors: Error[] }> {
const promises: Promise<void>[] = []
const errors: Error[] = []
@@ -111,6 +94,15 @@ export class CRMClient<T extends CRMConfig = CRMConfig> {
)
}
+ if (this.notion && options.notion) {
+ const { databaseId, properties } = options.notion
+ promises.push(
+ this.notion.createDatabasePage(databaseId, properties).catch((err) => {
+ errors.push(new Error(`Notion: ${err.message}`))
+ })
+ )
+ }
+
await Promise.all(promises)
return { errors }
diff --git a/packages/marketing/src/crm/notion.ts b/packages/marketing/src/crm/notion.ts
new file mode 100644
index 00000000000..c686823c303
--- /dev/null
+++ b/packages/marketing/src/crm/notion.ts
@@ -0,0 +1,124 @@
+import 'server-only'
+
+const NOTION_API_BASE = 'https://api.notion.com/v1'
+const NOTION_VERSION = '2022-06-28'
+
+export interface NotionConfig {
+ apiKey: string
+}
+
+interface NotionDatabaseProperty {
+ id: string
+ name: string
+ type: string
+}
+
+interface NotionDatabaseSchema {
+ properties: Record<string, NotionDatabaseProperty>
+}
+
+export class NotionClient {
+ private apiKey: string
+ private schemaCache = new Map<string, Promise<NotionDatabaseSchema>>()
+
+ constructor(config: NotionConfig) {
+ if (!config.apiKey) throw new Error('NotionClient: apiKey is required')
+ this.apiKey = config.apiKey
+ }
+
+ private async request<T>(path: string, method: 'GET' | 'POST', body?: unknown): Promise<T> {
+ const response = await fetch(`${NOTION_API_BASE}${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${this.apiKey}`,
+ 'Notion-Version': NOTION_VERSION,
+ 'Content-Type': 'application/json',
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ })
+
+ if (!response.ok) {
+ const errorText = await response.text()
+ throw new Error(`Notion API request failed: ${response.status} - ${errorText}`)
+ }
+
+ return (await response.json()) as T
+ }
+
+ private getSchema(databaseId: string): Promise<NotionDatabaseSchema> {
+ let pending = this.schemaCache.get(databaseId)
+ if (!pending) {
+ // databaseId is validated at the schema layer, but encodeURIComponent
+ // keeps this safe as defense-in-depth if the client ever grows a caller
+ // that bypasses the zod boundary.
+ pending = this.request<NotionDatabaseSchema>(
+ `/databases/${encodeURIComponent(databaseId)}`,
+ 'GET'
+ )
+ this.schemaCache.set(databaseId, pending)
+ }
+ return pending
+ }
+
+ /**
+ * Create a page in the given database. Property types are auto-detected from
+ * the database schema, so values can be passed as plain strings/numbers and
+ * will be wrapped in the correct Notion property shape.
+ * Unknown columns (not present in the database) are silently skipped.
+ */
+ async createDatabasePage(databaseId: string, values: Record<string, unknown>): Promise<void> {
+ const schema = await this.getSchema(databaseId)
+ const properties: Record<string, unknown> = {}
+
+ for (const [name, value] of Object.entries(values)) {
+ if (value === undefined || value === null || value === '') continue
+ const schemaProp = schema.properties[name]
+ if (!schemaProp) continue
+ const encoded = encodePropertyValue(schemaProp.type, value)
+ if (encoded !== undefined) properties[name] = encoded
+ }
+
+ await this.request('/pages', 'POST', {
+ parent: { database_id: databaseId },
+ properties,
+ })
+ }
+}
+
+function encodePropertyValue(type: string, value: unknown): unknown {
+ const str = typeof value === 'string' ? value : String(value)
+
+ switch (type) {
+ case 'title':
+ return { title: [{ text: { content: str } }] }
+ case 'rich_text':
+ return { rich_text: [{ text: { content: str } }] }
+ case 'email':
+ return { email: str }
+ case 'phone_number':
+ return { phone_number: str }
+ case 'url':
+ return { url: str }
+ case 'number': {
+ const n = typeof value === 'number' ? value : Number(str)
+ return Number.isFinite(n) ? { number: n } : undefined
+ }
+ case 'checkbox': {
+ const b = typeof value === 'boolean' ? value : str === 'true' || str === 'on'
+ return { checkbox: b }
+ }
+ case 'date':
+ return { date: { start: str } }
+ case 'select':
+ return { select: { name: str } }
+ case 'multi_select':
+ return {
+ multi_select: str
+ .split(',')
+ .map((s) => ({ name: s.trim() }))
+ .filter((o) => o.name),
+ }
+ default:
+ return { rich_text: [{ text: { content: str } }] }
+ }
+}
diff --git a/packages/marketing/src/go/actions/submitForm.ts b/packages/marketing/src/go/actions/submitForm.ts
index f9d37ea58ef..598d0462a65 100644
--- a/packages/marketing/src/go/actions/submitForm.ts
+++ b/packages/marketing/src/go/actions/submitForm.ts
@@ -24,37 +24,40 @@ function debug(message: string, data?: unknown) {
}
function buildCrmConfig(crm: GoFormCrmConfig): CRMConfig {
- const hubspotPortalId = process.env.HUBSPOT_PORTAL_ID
- const customerioSiteId = process.env.CUSTOMERIO_SITE_ID
- const customerioApiKey = process.env.CUSTOMERIO_API_KEY
+ const config: CRMConfig = {}
- if (crm.hubspot && crm.customerio) {
+ if (crm.hubspot) {
+ const hubspotPortalId = process.env.HUBSPOT_PORTAL_ID
if (!hubspotPortalId) throw new Error('HUBSPOT_PORTAL_ID env var is not set')
+ config.hubspot = { portalId: hubspotPortalId, formGuid: crm.hubspot.formGuid }
+ }
+
+ if (crm.customerio) {
+ const customerioSiteId = process.env.CUSTOMERIO_SITE_ID
+ const customerioApiKey = process.env.CUSTOMERIO_API_KEY
if (!customerioSiteId) throw new Error('CUSTOMERIO_SITE_ID env var is not set')
if (!customerioApiKey) throw new Error('CUSTOMERIO_API_KEY env var is not set')
- return {
- hubspot: { portalId: hubspotPortalId, formGuid: crm.hubspot.formGuid },
- customerio: { siteId: customerioSiteId, apiKey: customerioApiKey },
- }
+ config.customerio = { siteId: customerioSiteId, apiKey: customerioApiKey }
}
- if (crm.hubspot) {
- if (!hubspotPortalId) throw new Error('HUBSPOT_PORTAL_ID env var is not set')
- return { hubspot: { portalId: hubspotPortalId, formGuid: crm.hubspot.formGuid } }
+
+ if (crm.notion) {
+ const notionApiKey = process.env.NOTION_FORMS_API_KEY
+ if (!notionApiKey) throw new Error('NOTION_FORMS_API_KEY env var is not set')
+ config.notion = { apiKey: notionApiKey }
}
- // customerio only (guaranteed by schema refinement that at least one exists)
- if (!customerioSiteId) throw new Error('CUSTOMERIO_SITE_ID env var is not set')
- if (!customerioApiKey) throw new Error('CUSTOMERIO_API_KEY env var is not set')
- return { customerio: { siteId: customerioSiteId, apiKey: customerioApiKey } }
+
+ return config
}
/**
- * Submit form values to the configured CRM providers (HubSpot and/or Customer.io).
+ * Submit form values to the configured CRM providers (HubSpot, Customer.io, Notion).
*
* Credentials are read from environment variables:
* - HubSpot: HUBSPOT_PORTAL_ID
* - Customer.io: CUSTOMERIO_SITE_ID, CUSTOMERIO_API_KEY
+ * - Notion: NOTION_FORMS_API_KEY
*
- * Per-form config (formGuid, event name, field mappings) lives in the page definition.
+ * Per-form config (formGuid, event name, database_id, field mappings) lives in the page definition.
*/
export async function submitFormAction(
crm: GoFormCrmConfig,
@@ -85,6 +88,7 @@ export async function submitFormAction(
providers: Object.keys(crmConfig),
hubspot: crm.hubspot ? { formGuid: crm.hubspot.formGuid } : undefined,
customerio: crm.customerio ? { event: crm.customerio.event } : undefined,
+ notion: crm.notion ? { database_id: crm.notion.database_id } : undefined,
})
client = new CRMClient(crmConfig)
} catch (err: any) {
@@ -122,9 +126,24 @@ export async function submitFormAction(
})
}
- // submitEvent is typed via generics — cast to any to avoid fighting the conditional types
- // (the runtime behavior is correct: CRMClient checks which clients are configured)
- const { errors } = await (client as CRMClient).submitEvent({
+ // Build Notion page properties: map form fields via columnMap, then merge staticProperties
+ let notion: { databaseId: string; properties: Record<string, unknown> } | undefined
+ if (crm.notion) {
+ const columnMap = crm.notion.columnMap ?? {}
+ const properties: Record<string, unknown> = {}
+ for (const [formField, columnName] of Object.entries(columnMap)) {
+ if (formField in values) {
+ properties[columnName] = values[formField]
+ }
+ }
+ if (crm.notion.staticProperties) {
+ Object.assign(properties, crm.notion.staticProperties)
+ }
+ notion = { databaseId: crm.notion.database_id, properties }
+ debug('Notion payload', { databaseId: crm.notion.database_id, properties })
+ }
+
+ const { errors } = await client.submitEvent({
email,
hubspotFields,
context,
@@ -134,7 +153,8 @@ export async function submitFormAction(
? { ...(values as Record<string, unknown>), ...crm.customerio.staticProperties }
: undefined,
customerioProfile,
- } as any)
+ notion,
+ })
if (errors.length > 0) {
debug(
diff --git a/packages/marketing/src/go/schemas.ts b/packages/marketing/src/go/schemas.ts
index 7772143d153..d0b73469e26 100644
--- a/packages/marketing/src/go/schemas.ts
+++ b/packages/marketing/src/go/schemas.ts
@@ -136,11 +136,22 @@ export const formFieldSchema = z.discriminatedUnion('type', [
// ----- Form CRM config schemas -----
+/**
+ * Matches a UUID or a bare 32-char hex ID (Notion's database IDs often come
+ * without dashes). Used for values interpolated into outbound API URLs — the
+ * `crm` config travels over the server-action wire and must be treated as
+ * untrusted input.
+ */
+const uuidLikeIdSchema = z.union([
+ z.string().uuid(),
+ z.string().regex(/^[0-9a-f]{32}$/i, 'Must be a 32-character hex ID'),
+])
+
export const hubspotFormConfigSchema = z.object({
/**
* HubSpot form GUID. The portal ID is read from HUBSPOT_PORTAL_ID env var.
*/
- formGuid: z.string().min(1),
+ formGuid: uuidLikeIdSchema,
/**
* Map each form field `name` to a HubSpot field name.
* If omitted, the form field name is used as-is.
@@ -171,13 +182,35 @@ export const customerioFormConfigSchema = z.object({
staticProperties: z.record(z.string(), z.unknown()).optional(),
})
+export const notionFormConfigSchema = z.object({
+ /**
+ * Notion database ID to create a page in. The integration token is read
+ * from the NOTION_FORMS_API_KEY env var and must have write access to the database.
+ */
+ database_id: uuidLikeIdSchema,
+ /**
+ * Map each form field `name` to a Notion database column name.
+ * Only fields listed here are sent. Property types (title, rich_text,
+ * email, etc.) are auto-detected from the database schema.
+ * Example: { email_address: 'email', first_name: 'first_name' }
+ */
+ columnMap: z.record(z.string(), z.string()).optional(),
+ /**
+ * Static properties merged into the Notion page. Keys must match column
+ * names in the target database.
+ * Example: { source: 'Website Go Page' }
+ */
+ staticProperties: z.record(z.string(), z.unknown()).optional(),
+})
+
export const formCrmConfigSchema = z
.object({
hubspot: hubspotFormConfigSchema.optional(),
customerio: customerioFormConfigSchema.optional(),
+ notion: notionFormConfigSchema.optional(),
})
- .refine((v) => v.hubspot || v.customerio, {
- message: 'At least one CRM provider (hubspot or customerio) must be configured',
+ .refine((v) => v.hubspot || v.customerio || v.notion, {
+ message: 'At least one CRM provider (hubspot, customerio, or notion) must be configured',
})
export const formSectionSchema = z.object({
@@ -371,6 +404,7 @@ export type GoFormField = z.infer<typeof formFieldSchema>
export type GoFormSection = z.infer<typeof formSectionSchema>
export type GoHubSpotFormConfig = z.infer<typeof hubspotFormConfigSchema>
export type GoCustomerIOFormConfig = z.infer<typeof customerioFormConfigSchema>
+export type GoNotionFormConfig = z.infer<typeof notionFormConfigSchema>
export type GoFormCrmConfig = z.infer<typeof formCrmConfigSchema>
export type GoFeatureGridItem = z.infer<typeof featureGridItemSchema>
export type GoFeatureGridSection = z.infer<typeof featureGridSectionSchema>