: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { combineUrl } from 'kea-router'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { fileSystemTypes, productUrls } from '~/products'
import {
DataTableNode,
VisualizationNode,
HogQLFilters,
HogQLQuery,
ProductKey,
SharingConfigurationSettings,
} from '~/queries/schema/schema-general'
import { ActivityTab, OnboardingStepKey, SDKKey } from '~/types'
import type { MetricFormPrefill } from 'products/data_catalog/frontend/common'
import type { BillingSectionId } from './billing/types'
import type { BatchExportSceneTab } from './data-pipelines/batch-exports/BatchExportScene'
import { DataPipelinesNewSceneKind } from './data-pipelines/DataPipelinesNewScene'
import type { DestinationsSceneTab } from './data-pipelines/destinationsSceneLogic'
import { OutputTab } from './data-warehouse/editor/outputPaneLogic'
import type { HogFunctionSceneTab } from './hog-functions/HogFunctionScene'
import type { SettingId, SettingLevelId, SettingSectionId } from './settings/types'
/**
* To add a new URL to the front end:
* - add a URL function here
* - add a scene to the enum in sceneTypes.ts
* - add a scene configuration in scenes.ts
* - add a route to scene mapping in scenes.ts
* - and add a scene import in appScenes.ts
*
* Sync the paths with AutoProjectMiddleware!
*/
/** The filters the analytics list reads from its URL. */
export interface AnalyticsListUrlParams {
orderBy?: string
type?: string | string[]
createdBy?: string[]
folder?: string
search?: string
tags?: string[]
}
export const urls = {
...productUrls,
absolute: (path = ''): string => new URL(path, window.location.origin).href,
default: (): string => '/',
project: (id: string | number, path = ''): string => `/project/${id}` + path,
currentProject: (path = ''): string => urls.project(getCurrentTeamId(), path),
newTab: () => '/search',
eventDefinitions: (): string => '/data-management/events',
eventDefinition: (id: string | number): string => `/data-management/events/${id}`,
eventDefinitionEdit: (id: string | number): string => `/data-management/events/${id}/edit`,
propertyDefinitions: (type?: string): string => combineUrl('/data-management/properties', type ? { type } : {}).url,
// Virtual property ids contain `$`, which kea-router's segment charset rejects, so encode real ids
// (`:param` placeholders pass through untouched for route registration)
propertyDefinition: (id: string | number): string =>
`/data-management/properties/${typeof id === 'string' && id.startsWith(':') ? id : encodeURIComponent(id)}`,
propertyDefinitionEdit: (id: string | number): string =>
`/data-management/properties/${typeof id === 'string' && id.startsWith(':') ? id : encodeURIComponent(id)}/edit`,
schemaManagement: (): string => '/data-management/schema',
dataManagementHistory: (): string => '/data-management/history',
database: (): string => '/data-management/database',
dataWarehouseManagedViewsets: (): string => '/data-management/managed-viewsets',
webScripts: (): string => '/web-scripts',
webScriptsNew: (): string => '/web-scripts/new',
destinations: (tab?: DestinationsSceneTab): string => `/data-management/destinations${tab ? `?tab=${tab}` : ''}`,
transformations: (): string => '/data-management/transformations',
eventFiltering: (): string => '/data-management/event-filtering',
activity: (tab: ActivityTab | ':tab' = ActivityTab.ExploreEvents): string => `/activity/${tab}`,
event: (id: string, timestamp: string, eventName?: string): string =>
combineUrl(
`/events/${encodeURIComponent(id)}/${encodeURIComponent(timestamp)}`,
eventName ? { event: eventName } : {}
).url,
ingestionWarnings: (): string => '/data-management/ingestion-warnings',
ingestionWarningsV2: (): string => '/data-management/ingestion-warnings-v2',
revenueSettings: (): string => '/data-management/revenue',
coreEvents: (): string => '/data-management/core-events',
marketingAnalyticsApp: (): string => '/marketing',
customCss: (): string => '/themes/custom-css',
sqlEditor: ({
query,
view_id,
insightShortId,
draftId,
outputTab,
endpointName,
source,
connectionId,
executionTarget,
sendRawQuery,
dashboard,
tileGroupKey,
filters,
metricName,
metricPrefill,
}: {
/** Raw SQL, or a node whose visualization settings (display, chartSettings) should survive the trip */
query?: string | VisualizationNode | DataTableNode
view_id?: string
insightShortId?: string
draftId?: string
outputTab?: OutputTab
endpointName?: string
source?: string
connectionId?: string
executionTarget?: HogQLQuery['executionTarget']
sendRawQuery?: boolean
dashboard?: number
/** The dashboard tile group the saved insight goes into. Only applies with `dashboard`. */
tileGroupKey?: string | null
/** Applied on top of the opened query/insight — carries unsaved view-mode filter edits into the editor */
filters?: HogQLFilters
/** Opens the editor bound to this data catalog metric so its query can be updated in place */
metricName?: string
/** Seeds the editor's "Save as metric" dialog with values already typed in the new metric modal */
metricPrefill?: MetricFormPrefill
} = {}): string => {
const params = new URLSearchParams()
if (query) {
params.set('open_query', typeof query === 'string' ? query : JSON.stringify(query))
// With a view, the query opens as unsaved edits on top of that view
if (view_id) {
params.set('open_view', view_id)
}
} else if (view_id) {
params.set('open_view', view_id)
} else if (insightShortId) {
params.set('open_insight', insightShortId)
} else if (draftId) {
params.set('open_draft', draftId)
}
if (outputTab) {
params.set('output_tab', outputTab)
}
if (endpointName) {
params.set('endpoint_name', endpointName)
}
if (source) {
params.set('source', source)
}
if (metricName) {
params.set('edit_metric', metricName)
}
if (metricPrefill) {
const filledPrefill = Object.fromEntries(Object.entries(metricPrefill).filter(([, value]) => !!value))
if (Object.keys(filledPrefill).length) {
params.set('metric_prefill', JSON.stringify(filledPrefill))
}
}
if (dashboard) {
params.set('dashboard', String(dashboard))
if (tileGroupKey) {
params.set('tile_group', tileGroupKey)
}
}
const queryString = params.toString()
const hashParams = new URLSearchParams()
if (connectionId) {
hashParams.set('c', connectionId)
}
if (executionTarget) {
hashParams.set('engine', executionTarget === 'managed_trino' ? 'managed_trino' : 'posthog')
}
if (sendRawQuery) {
hashParams.set('raw', '1')
}
if (filters) {
hashParams.set('filters', JSON.stringify(filters))
}
const hashString = hashParams.toString()
return `/sql${queryString ? `?${queryString}` : ''}${hashString ? `#${hashString}` : ''}`
},
variables: (): string => '/data-management/variables',
variable: (id: string | ':id'): string => `/data-management/variables/${id}`,
variableEdit: (id: string | ':id'): string => `/data-management/variables/${id}/edit`,
resourceTransfer: (resourceKind: string, resourceId: string | number, insightShortId?: string): string =>
combineUrl(`/resource-transfer/${resourceKind}/${resourceId}`, { insight_short_id: insightShortId }).url,
dashboardTemplateCopyToProject: (templateId: string | ':sourceTemplateId', sourceTeamId?: number): string => {
const path = `/dashboard/templates/${templateId}/copy-to-project`
return sourceTeamId === undefined
? path
: combineUrl(path, {
source_team: sourceTeamId,
}).url
},
organizationCreateFirst: (): string => '/create-organization',
projectCreateFirst: (): string => '/organization/create-project',
projectRoot: (): string => '/',
projectHomepage: (): string => '/home',
todayReport: (reportId: string): string => `/home/reports/${reportId}`,
library: (objectType?: string): string => (objectType ? `/library/${objectType}` : '/library'),
analytics: (): string => '/analytics',
analyticsList: (params: AnalyticsListUrlParams = {}): string => combineUrl('/analytics/all', params).url,
analyticsMine: (params: AnalyticsListUrlParams = {}): string => combineUrl('/analytics/mine', params).url,
analyticsSpaces: (): string => '/analytics/spaces',
analyticsProductHome: (): string => '/analytics/product-analytics',
tools: (): string => '/tools',
ai: (chat?: string, ask?: string): string => combineUrl('/ai', { ask, chat }).url,
aiTask: (taskId: string): string => combineUrl('/ai', { task: taskId }).url,
aiHistory: (): string => '/ai/history',
settings: (section: SettingSectionId | SettingLevelId = 'project', setting?: SettingId): string =>
combineUrl(`/settings/${section}`, undefined, setting).url,
identityProviderConfig: (
feature: 'saml' | 'oidc' | 'scim' | 'xaa' | ':feature',
configId: string | ':configId'
): string => `/settings/organization-authentication/${feature}/${configId}`,
featurePreview: (flagKey: string): string => combineUrl('/settings/user-feature-previews', {}, flagKey).url,
organizationCreationConfirm: (): string => '/organization/confirm-creation',
toolbarLaunch: (): string => '/toolbar',
site: (url: string): string => `/site/${url === ':url' ? url : encodeURIComponent(url)}`,
// Onboarding / setup routes
login: (): string => '/login',
login2FA: (): string => '/login/2fa',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
login2FASetup: (): string => '/login/2fa_setup',
/** After linking a social provider to an existing session (OAuth `next`; see posthog/api/authentication.py sso_login). */
accountSocialConnected: (): string => '/account/social-connected',
/**
* PostHog Desktop / web return page after connecting an account. Use `github-login` (social SSO),
* `github-integration` (user GitHub App integration), or `slack-integration` (team Slack integration);
* see `AccountConnected` and `posthog/api/authentication.py` / `user_integration.py`.
*/
accountConnected: (kind: string = ':kind'): string =>
kind === ':kind' ? '/account-connected/:kind' : `/account-connected/${kind}`,
/** One-shot credential review interstitial shown to users with existing API keys they haven't acknowledged. */
credentialReview: (next?: string): string =>
`/account/credential-review${next ? `?next=${encodeURIComponent(next)}` : ''}`,
cliAuthorize: (): string => '/cli/authorize',
// pinned: the OAuth server sends devices here as verification_uri, see posthog/api/oauth/device.py
oauthDeviceAuthorize: (): string => '/device',
cliLive: (): string => '/cli/live',
passwordReset: (): string => '/reset',
passwordResetComplete: (userUuid: string, token: string): string => `/reset/${userUuid}/${token}`,
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
twoFactorReset: (userUuid: string, token: string): string => `/reset_2fa/${userUuid}/${token}`,
preflight: (): string => '/preflight',
signup: (): string => '/signup',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
verifyEmail: (userUuid: string = ''): string => `/verify_email${userUuid ? `/${userUuid}` : ''}`,
vercelConnect: (): string => '/connect/vercel/link',
vercelLinkError: (): string => '/integrations/vercel/link-error',
agenticAccountMismatch: (): string => '/agentic/account-mismatch',
inviteSignup: (id: string): string => `/signup/${id}`,
onboarding: ({
campaign,
productKey,
stepKey,
step,
sdk,
withProducts,
}: {
campaign?: string
productKey?: string
stepKey?: OnboardingStepKey
// Namespaced step ID (e.g. `install:logs`). Takes precedence over `stepKey` when both are passed.
step?: string
sdk?: SDKKey
/** Other products to include in the flow alongside the primary (comma-joined in the URL). */
withProducts?: string[]
} = {}): string => {
if (campaign) {
return `/onboarding/coupons/${campaign}`
}
const params = new URLSearchParams()
if (step) {
params.set('step', step)
} else if (stepKey) {
params.set('step', stepKey)
}
if (sdk) {
params.set('sdk', sdk)
}
if (withProducts?.length) {
params.set('with', withProducts.join(','))
}
const base = `/onboarding${productKey ? `/${productKey}` : ''}`
const queryString = params.toString()
return `${base}${queryString ? `?${queryString}` : ''}`
},
onboardingWelcome: (): string => '/welcome',
// Cloud only
organizationBilling: (products?: ProductKey[]): string =>
`/organization/billing${products && products.length ? `?products=${products.join(',')}` : ''}`,
organizationBillingSection: (section: BillingSectionId = 'overview'): string =>
combineUrl(`/organization/billing/${section}`).url,
organizationBillingRealTimeUsage: (): string => '/organization/billing/real-time-usage',
advancedActivityLogs: (): string => '/activity-logs',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
billingAuthorizationStatus: (): string => `/billing/authorization_status`,
// Self-hosted only
instanceStatus: (): string => '/instance/status',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
instanceStaffUsers: (): string => '/instance/staff_users',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
instanceKafkaInspector: (): string => '/instance/kafka_inspector',
instanceSettings: (): string => '/instance/settings',
instanceMetrics: (): string => `/instance/metrics`,
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
asyncMigrations: (): string => '/instance/async_migrations',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
asyncMigrationsFuture: (): string => '/instance/async_migrations/future',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
asyncMigrationsSettings: (): string => '/instance/async_migrations/settings',
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
deadLetterQueue: (): string => '/instance/dead_letter_queue',
materializedColumns: (): string => '/data-management/materialized-columns',
unsubscribe: (): string => '/unsubscribe',
codeCanvasLink: (channelId: string, dashboardId: string): string => `/code/canvas/${channelId}/${dashboardId}`,
codeChannelLink: (channelId: string, taskId?: string): string =>
`/code/channel/${channelId}${taskId ? `/tasks/${taskId}` : ''}`,
codeTaskLink: (taskId: string): string => `/code/task/${taskId}`,
codeLoopLink: (loopId: string): string => `/code/loop/${loopId}`,
integration: (slug: string): string => `/integrations/${slug}`,
integrationsRedirect: (kind: string): string => `/integrations/${kind}/callback`,
stripeConfirmInstall: (): string => '/integrations/stripe/confirm-install',
shared: (token: string, exportOptions: SharingConfigurationSettings = {}): string =>
combineUrl(
`/shared/${token}`,
Object.entries(exportOptions)
// strip falsey values
.filter((x) => x[1])
.reduce(
(acc, [key, val]) =>
Object.assign(acc, {
// just sends the key and not a value
// e.g., &showInspector not &showInspector=true
[key]: val === true ? null : val,
}),
{}
)
).url,
embedded: (token: string, exportOptions?: SharingConfigurationSettings): string =>
urls.shared(token, exportOptions).replace('/shared/', '/embedded/'),
debugQuery: (query?: string | Record<string, any>): string =>
combineUrl('/debug', {}, query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}).url,
debugHog: (): string => '/debug/hog',
terminal: (): string => '/terminal',
projectFiles: (folder = ''): string => combineUrl('/files', folder ? { folder } : {}).url,
moveToPostHogCloud: (): string => '/move-to-cloud',
sessionAttributionExplorer: (): string => '/web/session-attribution-explorer',
sessionProfile: (id: string): string => `/sessions/${id}`,
coupons: (campaign: string): string => `/coupons/${campaign}`,
startups: (referrer?: string): string => `/startups${referrer ? `/${referrer}` : ''}`,
organizationStartups: (referrer?: string): string => `/organization/startups${referrer ? `/${referrer}` : ''}`,
agenticAuthorize: (): string => '/agentic/authorize',
oauthAuthorize: (): string => '/oauth/authorize',
dataPipelinesNew: (kind?: DataPipelinesNewSceneKind): string => `/pipeline/new/${kind ?? ''}`,
batchExportNew: (service: string): string => `/pipeline/batch-exports/new/${service}`,
batchExport: (id: string, tab?: BatchExportSceneTab): string =>
`/pipeline/batch-exports/${id}${tab ? `?tab=${tab}` : ''}`,
legacyPlugin: (id: string): string => `/pipeline/plugins/${id}`,
hogFunction: (id: string, tab?: HogFunctionSceneTab): string => `/functions/${id}${tab ? `?tab=${tab}` : ''}`,
hogFunctionNew: (templateId: string): string => `/functions/new/${templateId}`,
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
productTours: (): string => '/product_tours',
productTour: (id: string, params?: string): string =>
// nosemgrep: frontend-url-hyphen -- shipped app URL, existing links point here
`/product_tours/${id}${params ? `?${params.startsWith('?') ? params.slice(1) : params}` : ''}`,
organizationDeactivated: (): string => '/organization-deactivated',
organizationPendingDeletion: (): string => '/organization-pending-deletion',
projectPendingDeletion: (): string => '/project-pending-deletion',
approvals: (): string => '/settings/environment-approvals#change-requests',
approval: (id: string): string => `/approvals/${id}`,
workloadTrustPolicyRequest: (id: string): string => `/workload-trust-policy-requests/${id}`,
health: (): string => '/health',
healthCategory: (category: string): string => `/health/${category}`,
healthAlerts: (presetKinds?: string[]): string =>
presetKinds && presetKinds.length > 0
? `/health/alerts?preset_kinds=${encodeURIComponent(presetKinds.join(','))}`
: '/health/alerts',
webAnalyticsBotAnalytics: (): string => '/web/bots',
webAnalyticsPagePerformance: (): string => '/web/page-performance',
webAnalyticsAgents: (): string => '/web/agents',
webAnalyticsHealth: (): string => '/web/health',
webAnalyticsRecap: (): string => '/web/recap',
pipelineStatus: (): string => '/health/pipeline-status',
sdkHealth: (): string => '/health/sdk-health',
exports: (): string => '/exports',
}
export interface UrlMatcher {
type?: string
matchers: Record<string, UrlMatcher>
}
const rootMatcher: UrlMatcher = { matchers: {} }
for (const [type, { href }] of Object.entries(fileSystemTypes)) {
if (typeof href !== 'function') {
continue
}
const computed = href(':id') // e.g. "/insights/:id"
const pathname = computed.split('?')[0]
// Normalize and split: "/insights/:id" -> ["insights", ":id"]
const parts = pathname
.replace(/^\/+|\/+$/g, '') // trim leading/trailing slashes
.split('/')
.filter(Boolean)
if (!parts.includes(':id')) {
continue
}
let node = rootMatcher
for (const part of parts) {
if (!node.matchers[part]) {
node.matchers[part] = { matchers: {} }
}
node = node.matchers[part]
if (part === ':id') {
node.type = type
}
}
}
export function urlToResource(url: string): { type: string; ref: string } | null {
const pathname = url.split('?')[0]
const parts = pathname
.replace(/^\/+|\/+$/g, '')
.split('/')
.filter(Boolean)
let node: UrlMatcher = rootMatcher
let id: string | null = null
for (const part of parts) {
if (node.matchers[part]) {
node = node.matchers[part]
continue
}
if (node.matchers[':id']) {
node = node.matchers[':id']
id = part
continue
}
return null
}
if (node.type && id !== null) {
return { type: node.type, ref: id }
}
return null
}