: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
feat(auth): add search and link-preview metadata to login and signup (#112980)
Rafael Audibert3e42420722f9
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.tsindex c4c2c5e32723..53e086d097b0 100644--- a/frontend/src/scenes/scenes.ts+++ b/frontend/src/scenes/scenes.ts@@ -260,7 +260,7 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {iconType: 'live',},[Scene.Login2FA]: { onlyUnauthenticated: true, name: 'Login 2FA', layout: 'plain' },- [Scene.Login]: { onlyUnauthenticated: true, layout: 'plain' },+ [Scene.Login]: { onlyUnauthenticated: true, name: 'Log in', layout: 'plain' },[Scene.Max]: { projectBased: true, name: 'Max', layout: 'app-raw-no-header', hideProjectNotice: true },[Scene.MoveToPostHogCloud]: { name: 'Move to PostHog Cloud', hideProjectNotice: true },[Scene.NewTab]: {@@ -479,7 +479,7 @@ export const sceneConfigurations: Record<Scene | string, SceneConfig> = {[Scene.SessionProfile]: { projectBased: true, name: 'Session profile', iconType: 'session_profile' },[Scene.Settings]: { projectBased: true, name: 'Settings' },[Scene.IdentityProviderConfig]: { projectBased: true, name: 'Configure identity provider' },- [Scene.Signup]: { onlyUnauthenticated: true, layout: 'plain' },+ [Scene.Signup]: { onlyUnauthenticated: true, name: 'Sign up', layout: 'plain' },[Scene.Site]: { projectBased: true, hideProjectNotice: true, layout: 'app-raw' },[Scene.StartupProgram]: { name: 'PostHog for Startups', organizationBased: true, layout: 'plain' },[Scene.SurveyWizard]: {diff --git a/posthog/frontend_views.py b/posthog/frontend_views.pyindex 42b013231543..c532a2c7e85e 100644--- a/posthog/frontend_views.py+++ b/posthog/frontend_views.py@@ -1,10 +1,13 @@+import jsonfrom typing import Anyfrom urllib.parse import urlparse+from django.conf import settingsfrom django.http import HttpRequest, HttpResponse, HttpResponseRedirectfrom django.utils.http import url_has_allowed_host_and_schemefrom django.views.decorators.csrf import ensure_csrf_cookie+from posthog.dataclasses import frozenfrom posthog.models.instance_setting import get_instance_settingfrom posthog.utils import render_templatefrom posthog.views import login_required@@ -15,6 +18,82 @@ APP_POSTHOG_HOST = "app.posthog.com"_REGION_HOSTS = {"us.posthog.com", "eu.posthog.com"}+@frozen+class _PageMetadata:+ title: str+ description: str+++# Same share image as posthog.com, so links to the app and the website preview alike.+_PREVIEW_IMAGE_URL = "https://posthog.com/images/og/default.png"++# Each title matches the document title the SPA sets for the scene, so the tab title doesn't change when the app boots.+_PUBLIC_PAGE_METADATA: dict[str, _PageMetadata] = {+ "/login": _PageMetadata(+ title="Log in • PostHog",+ description="Log in to PostHog, the single platform for engineers to analyze, test, observe, and deploy new features.",+ ),+ "/signup": _PageMetadata(+ title="Sign up • PostHog",+ description=(+ "Create a free PostHog account to analyze, test, observe, and deploy new features. "+ "Every product has a monthly free tier, and no credit card is required."+ ),+ ),+}+++def _structured_data_json(metadata: _PageMetadata, canonical_url: str) -> str:+ structured_data = {+ "@context": "https://schema.org",+ "@type": "WebPage",+ "name": metadata.title,+ "description": metadata.description,+ "url": canonical_url,+ "isPartOf": {"@type": "WebSite", "name": "PostHog", "url": settings.SITE_URL},+ "about": {+ "@type": "SoftwareApplication",+ "name": "PostHog",+ "applicationCategory": "BusinessApplication",+ "operatingSystem": "Web",+ "url": "https://posthog.com",+ "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"},+ },+ # Matches the Organization that posthog.com publishes, so search engines tie the app to the same entity.+ "publisher": {+ "@type": "Organization",+ "name": "PostHog",+ "url": "https://posthog.com",+ "logo": "https://posthog.com/brand/posthog-logo-stacked.png",+ "sameAs": [+ "https://twitter.com/PostHog",+ "https://github.com/PostHog",+ "https://www.linkedin.com/company/posthog",+ ],+ },+ }+ # The template renders this inside <script> with |safe, so no character may close the element.+ return json.dumps(structured_data).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")+++def public_page_metadata_context(request: HttpRequest) -> dict[str, str]:+ """Template context for the search and link-preview tags of a public page, or an empty+ dict for every other path. The canonical URL drops the query string, so links such as+ `/login?next=...` count as one page."""+ path = request.path.rstrip("/")+ metadata = _PUBLIC_PAGE_METADATA.get(path)+ if metadata is None:+ return {}+ canonical_url = f"{settings.SITE_URL}{path}"+ return {+ "page_title": metadata.title,+ "page_description": metadata.description,+ "canonical_url": canonical_url,+ "preview_image_url": _PREVIEW_IMAGE_URL,+ "structured_data_json": _structured_data_json(metadata, canonical_url),+ }++def region_host_from_current_instance(cookie_value: str | None) -> str | None:"""Map a `ph_current_instance` cookie (an instance SITE_URL) to its canonical regionhost, or None when it isn't a recognized cloud region. Mirrors the frontend@@ -54,7 +133,7 @@ def app_region_redirect(request: HttpRequest) -> HttpResponseRedirect | None:@ensure_csrf_cookiedef _render_home(request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:- return render_template("index.html", request)+ return render_template("index.html", request, public_page_metadata_context(request))# Wrapped once at import time (as `login_required(home)` used to be) so the catch-alldiff --git a/posthog/templates/head.html b/posthog/templates/head.htmlindex 9f068544a982..e3f5810917b9 100644--- a/posthog/templates/head.html+++ b/posthog/templates/head.html@@ -1,4 +1,4 @@-<title>PostHog</title>+<title>{{ page_title|default:"PostHog" }}</title><meta name="viewport" content="width=device-width, initial-scale=1"><meta charset="utf-8">{% for token in origin_trial_tokens %}@@ -27,6 +27,20 @@<link rel="manifest" href="/static/site.webmanifest?v=2026-07-07"><meta name="apple-mobile-web-app-title" content="PostHog"><meta name="application-name" content="PostHog">+{% if page_description %}+ <meta name="description" content="{{ page_description }}">+ <link rel="canonical" href="{{ canonical_url }}">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="PostHog">+ <meta property="og:title" content="{{ page_title }}">+ <meta property="og:description" content="{{ page_description }}">+ <meta property="og:url" content="{{ canonical_url }}">+ <meta property="og:image" content="{{ preview_image_url }}">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@PostHog">+ {# nosemgrep: python.flask.security.xss.audit.template-unescaped-with-safe.template-unescaped-with-safe, generic.html-templates.security.var-in-script-tag.var-in-script-tag (_structured_data_json escapes "<", ">" and "&", so the JSON cannot end the script element) #}+ <script type="application/ld+json">{{ structured_data_json|safe }}</script>+{% endif %}{% if not opt_out_capture and js_posthog_api_key %}{{ posthog_bootstrap|page_json_script:"posthog-user-identity-with-flags" }}{% if js_posthog_identity_distinct_id and js_posthog_identity_claims %}diff --git a/posthog/test/test_urls.py b/posthog/test/test_urls.pyindex 1111974c38c4..431f2a59a3a2 100644--- a/posthog/test/test_urls.py+++ b/posthog/test/test_urls.py@@ -1,3 +1,4 @@+import jsonimport uuidimport importlib.utilfrom itertools import product@@ -5,6 +6,7 @@ from pathlib import Pathfrom posthog.test.base import APIBaseTest+from django.template.loader import render_to_stringfrom django.test import RequestFactory, SimpleTestCase, override_settingsfrom django.urls import URLResolver, resolvefrom django.urls.resolvers import RegexPattern@@ -14,7 +16,12 @@ from rest_framework import statusfrom posthog import urlsfrom posthog.api.playwright_setup import delete_events-from posthog.frontend_views import home, home_with_region_redirect, region_host_from_current_instance+from posthog.frontend_views import (+ home,+ home_with_region_redirect,+ public_page_metadata_context,+ region_host_from_current_instance,+)from posthog.models.instance_setting import override_instance_configfrom posthog.temporal.codec_server import decode_payloadsfrom posthog.views import handler500, metrics_view@@ -211,6 +218,36 @@ class TestRegionHostFromCurrentInstance(SimpleTestCase):self.assertEqual(region_host_from_current_instance(cookie_value), expected)+class TestPublicPageMetadata(SimpleTestCase):+ @parameterized.expand(+ [+ ("login_with_next", "/login?next=/insights", "Log in • PostHog", "/login"),+ ("signup_with_email", "/signup/?email=someone%40example.com", "Sign up • PostHog", "/signup"),+ ("preflight", "/preflight", "PostHog", None),+ ("invite_signup", "/signup/0b8e1f2a-1111-4c2d-9e3f-123456789abc", "PostHog", None),+ ]+ )+ @override_settings(SITE_URL="https://us.example.com")+ def test_head_renders_search_metadata(self, _name, request_path, expected_title, expected_canonical_path):+ request = RequestFactory().get(request_path)+ html = render_to_string("head.html", public_page_metadata_context(request))++ self.assertIn(f"<title>{expected_title}</title>", html)+ if expected_canonical_path is None:+ self.assertNotIn('rel="canonical"', html)+ self.assertNotIn('name="description"', html)+ self.assertNotIn("application/ld+json", html)+ else:+ canonical_url = f"https://us.example.com{expected_canonical_path}"+ self.assertIn(f'<link rel="canonical" href="{canonical_url}">', html)+ self.assertIn(f'<meta property="og:url" content="{canonical_url}">', html)+ self.assertIn('<meta name="description" content="', html)+ structured_data = json.loads(html.split('<script type="application/ld+json">')[1].split("</script>")[0])+ self.assertEqual(structured_data["@type"], "WebPage")+ self.assertEqual(structured_data["url"], canonical_url)+ self.assertEqual(structured_data["name"], expected_title)++class TestLegacyDuckgresAdminUrls(SimpleTestCase):@parameterized.expand([