Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: environment mapping for Vercel connectable integrations (#53492)

Matt Brookerd21ad984b92d
diff --git a/frontend/src/lib/integrations/IntegrationView.tsx b/frontend/src/lib/integrations/IntegrationView.tsx
index d04b87f1a6d7..308e0d3eba7b 100644
--- a/frontend/src/lib/integrations/IntegrationView.tsx
+++ b/frontend/src/lib/integrations/IntegrationView.tsx
@@ -62,7 +62,7 @@ export function IntegrationView({
return (
<div className="rounded border bg-surface-primary">
- <div className="flex justify-between items-center p-2">
+ <div className="flex flex-wrap justify-between items-center p-2 gap-2">
<div className="flex gap-4 items-center ml-2">
<img
src={integration.icon_url}
diff --git a/frontend/src/lib/integrations/VercelIntegrationSuffix.tsx b/frontend/src/lib/integrations/VercelIntegrationSuffix.tsx
index c9f95455eda8..fd8296da8351 100644
--- a/frontend/src/lib/integrations/VercelIntegrationSuffix.tsx
+++ b/frontend/src/lib/integrations/VercelIntegrationSuffix.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useEffect, useState } from 'react'
+import { Fragment, useEffect, useState } from 'react'
import { IconTrash } from '@posthog/icons'
import { LemonButton, LemonSelect } from '@posthog/lemon-ui'
@@ -45,7 +45,7 @@ export function VercelIntegrationSuffix({ integration }: { integration: Integrat
const isConnectable = integration.config?.type === 'connectable'
const envMapping: EnvMapping | undefined = integration.config?.environment_mapping
- if (!isConnectable || !envMapping) {
+ if (!isConnectable) {
return (
<div className="flex gap-2">
{accountUrl && (
@@ -64,12 +64,13 @@ export function VercelIntegrationSuffix({ integration }: { integration: Integrat
)
}
+ const effectiveMapping = envMapping || { production: null, preview: null, development: null }
return (
<div>
<div className="flex justify-end">
<DisconnectButton integration={integration} />
</div>
- <VercelEnvMappingEditor integration={integration} envMapping={envMapping} />
+ <VercelEnvMappingEditor integration={integration} envMapping={effectiveMapping} />
</div>
)
}
@@ -99,29 +100,31 @@ function VercelEnvMappingEditor({
setDirty(true)
}
- const handleSave = (): void => {
+ const handleSave = async (): Promise<void> => {
setSaving(true)
setError(null)
- fetch(`/api/organizations/@current/integrations/${integration.id}/environment-mapping/`, {
- method: 'PATCH',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': getCookie('posthog_csrftoken') || '',
- },
- body: JSON.stringify({
- production: mapping.production,
- preview: mapping.preview || mapping.production,
- development: mapping.development || mapping.production,
- }),
- })
- .then((res) => {
- if (!res.ok) {
- throw new Error('Failed to save')
- }
- setDirty(false)
+ try {
+ const res = await fetch(`/api/organizations/@current/integrations/${integration.id}/environment-mapping/`, {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCookie('posthog_csrftoken') || '',
+ },
+ body: JSON.stringify({
+ production: mapping.production,
+ preview: mapping.preview || mapping.production,
+ development: mapping.development || mapping.production,
+ }),
})
- .catch(() => setError('Failed to save environment mapping'))
- .finally(() => setSaving(false))
+ if (!res.ok) {
+ throw new Error('Failed to save')
+ }
+ setDirty(false)
+ } catch {
+ setError('Failed to save environment mapping')
+ } finally {
+ setSaving(false)
+ }
}
const teamOptions = teams.map((t) => ({
@@ -130,23 +133,31 @@ function VercelEnvMappingEditor({
}))
return (
- <div className="space-y-2 w-full mt-2">
- <h4 className="font-semibold text-sm">Environment mapping</h4>
- {(['production', 'preview', 'development'] as const).map((env) => (
- <div key={env} className="flex items-center gap-2">
- <span className="text-xs font-medium text-muted uppercase w-24">{env}</span>
- <LemonSelect
- size="small"
- fullWidth
- value={mapping[env]}
- onChange={(value) => handleChange(env, value)}
- options={teamOptions}
- />
- </div>
- ))}
+ <div className="basis-full border-t pt-3 mt-1 mx-2 mb-2 space-y-2">
+ <h4 className="font-semibold text-xs text-muted">Environment mapping</h4>
+ <div className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 items-center max-w-sm">
+ {(['production', 'preview', 'development'] as const).map((env) => (
+ <Fragment key={env}>
+ <span className="text-xs font-medium text-muted uppercase">{env}</span>
+ <LemonSelect
+ size="small"
+ fullWidth
+ value={mapping[env]}
+ onChange={(value) => handleChange(env, value)}
+ options={teamOptions}
+ />
+ </Fragment>
+ ))}
+ </div>
{error && <p className="text-danger text-xs">{error}</p>}
{dirty && (
- <LemonButton type="primary" size="small" loading={saving} onClick={handleSave}>
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={saving}
+ disabledReason={!mapping.production ? 'Production project is required' : undefined}
+ onClick={handleSave}
+ >
Save mapping
</LemonButton>
)}
diff --git a/frontend/src/lib/integrations/organizationIntegrationConfig.tsx b/frontend/src/lib/integrations/organizationIntegrationConfig.tsx
index 846bb5b39b7b..a4c4d3f25e06 100644
--- a/frontend/src/lib/integrations/organizationIntegrationConfig.tsx
+++ b/frontend/src/lib/integrations/organizationIntegrationConfig.tsx
@@ -10,7 +10,7 @@ export type OrganizationIntegrationConfig = {
const INTEGRATION_CONFIGS: Partial<Record<IntegrationKind, OrganizationIntegrationConfig>> = {
vercel: {
getSuffix: (integration) => <VercelIntegrationSuffix integration={integration} />,
- getDisplayName: (integration) => integration.config?.account?.name || integration.display_name,
+ getDisplayName: (integration) => integration.config?.account?.name || integration.display_name || 'Vercel',
},
}
diff --git a/posthog/api/organization_integration.py b/posthog/api/organization_integration.py
index cd3dc44dee84..0863351b6332 100644
--- a/posthog/api/organization_integration.py
+++ b/posthog/api/organization_integration.py
@@ -132,12 +132,12 @@ class OrganizationIntegrationViewSet(
from posthog.models.integration import Integration as TeamIntegration
from ee.vercel.client import VercelAPIClient
- from ee.vercel.integration import VercelIntegration
teams_by_id: dict[int, Team] = {}
+ resources: dict[int, TeamIntegration] = {}
for tid in {production_id, preview_id, development_id}:
teams_by_id[tid] = Team.objects.get(pk=tid, organization=org)
- TeamIntegration.objects.get_or_create(
+ resources[tid], _ = TeamIntegration.objects.get_or_create(
team=teams_by_id[tid],
kind=TeamIntegration.IntegrationKind.VERCEL,
integration_id=str(tid),
@@ -152,44 +152,17 @@ class OrganizationIntegrationViewSet(
integration.save(update_fields=["config"])
production_team = teams_by_id[production_id]
- preview_team = teams_by_id[preview_id]
- dev_team = teams_by_id[development_id]
-
- production_resource = TeamIntegration.objects.filter(
- team=production_team, kind=TeamIntegration.IntegrationKind.VERCEL
- ).first()
-
- if not production_resource:
- return Response(
- {"detail": "Failed to find or create production resource. Please reconnect the integration."},
- status=500,
- )
+ production_resource = resources[production_id]
access_token = integration.sensitive_config.get("credentials", {}).get(
"access_token"
) or integration.config.get("credentials", {}).get("access_token")
if access_token and integration.integration_id:
- all_same = production_id == preview_id == development_id
- secrets: list[dict[str, Any]] = [
- {
- "name": "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN",
- "value": production_team.api_token,
- **(
- {}
- if all_same
- else {
- "environmentOverrides": {
- **({"preview": preview_team.api_token} if preview_id != production_id else {}),
- **({"development": dev_team.api_token} if development_id != production_id else {}),
- }
- }
- ),
- },
- {
- "name": "NEXT_PUBLIC_POSTHOG_HOST",
- "value": VercelIntegration._build_secrets(production_team)[1]["value"],
- },
- ]
+ from ee.api.vercel.vercel_connect import VercelConnectLinkViewSet
+
+ secrets = VercelConnectLinkViewSet._build_env_secrets(
+ teams_by_id, production_id, preview_id, development_id
+ )
client = VercelAPIClient(bearer_token=access_token)
client.import_resource(
integration_config_id=integration.integration_id,