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(projects): reject duplicate project names within an organization (#77399)

Eleftheria Trivyzaki0c494a100694
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 2ae909d7f004..eee17cfa04d8 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1612,7 +1612,7 @@ export interface ProjectBackwardCompatApi {
readonly id: number
readonly organization: string
/**
- * Human-readable project name.
+ * Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.
* @minLength 1
* @maxLength 200
*/
@@ -2464,7 +2464,7 @@ export interface PatchedProjectBackwardCompatApi {
readonly id?: number
readonly organization?: string
/**
- * Human-readable project name.
+ * Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.
* @minLength 1
* @maxLength 200
*/
diff --git a/frontend/src/scenes/project/CreateProjectModal.tsx b/frontend/src/scenes/project/CreateProjectModal.tsx
index 2a943bfd53e7..393248863d19 100644
--- a/frontend/src/scenes/project/CreateProjectModal.tsx
+++ b/frontend/src/scenes/project/CreateProjectModal.tsx
@@ -35,6 +35,10 @@ export function CreateProjectModal({
const { reportProjectCreationSubmitted } = useActions(eventUsageLogic)
const [name, setName] = useState<string>('')
+ const isNameTaken = !!currentOrganization?.projects?.some(
+ (project) => project.name.trim().toLowerCase() === name.trim().toLowerCase()
+ )
+
const closeModal: () => void = () => {
if (onClose) {
onClose()
@@ -44,6 +48,10 @@ export function CreateProjectModal({
}
}
const handleSubmit = (): void => {
+ // Also guards Enter-key submission, which bypasses the button's disabledReason
+ if (!name || isNameTaken || currentProjectLoading) {
+ return
+ }
createProject({ name })
reportProjectCreationSubmitted(
currentOrganization?.projects ? currentOrganization.projects.length : 0,
@@ -103,7 +111,13 @@ export function CreateProjectModal({
type="primary"
onClick={handleSubmit}
loading={currentProjectLoading}
- disabledReason={!name ? 'Think of a name!' : null}
+ disabledReason={
+ !name
+ ? 'Think of a name!'
+ : isNameTaken
+ ? 'There is already a project with this name in this organization. Choose a different name.'
+ : null
+ }
>
Create project
</LemonButton>
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 1594d23a0152..595a9ad1adad 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -5,6 +5,7 @@ from typing import Any, Optional, cast
from django.conf import settings
from django.db import transaction
from django.db.models import Model
+from django.db.models.functions import Trim
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.dateparse import parse_datetime
@@ -51,6 +52,7 @@ from posthog.cloud_utils import get_cached_instance_license, is_cloud
from posthog.constants import AvailableFeature
from posthog.decorators import disallow_if_impersonated
from posthog.event_usage import report_user_action
+from posthog.exceptions import Conflict
from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
@@ -584,6 +586,12 @@ class ProjectBackwardCompatSerializer(
project_id = serializers.IntegerField(
source="id", read_only=True, help_text="ID of the project this environment belongs to."
)
+ name = serializers.CharField(
+ required=False,
+ min_length=1,
+ max_length=200,
+ help_text="Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.",
+ )
# Analytics config sub-objects live on the passthrough Team — reuse the Team serializers for identical shape
revenue_analytics_config = TeamRevenueAnalyticsConfigSerializer(required=False) # Compat with TeamSerializer
marketing_analytics_config = TeamMarketingAnalyticsConfigSerializer(required=False) # Compat with TeamSerializer
@@ -980,6 +988,30 @@ class ProjectBackwardCompatSerializer(
def get_available_setup_task_ids(self, obj) -> list[str]:
return [e.value for e in SetupTaskId]
+ def validate_name(self, value: str) -> str:
+ value = value.strip()
+ # A no-op save must stay valid even for projects that already share a name from before
+ # duplicate names were rejected, so only newly chosen names are checked.
+ if self.instance is not None and value == self.instance.name:
+ return value
+ organization_id = (
+ self.instance.organization_id if self.instance is not None else self.context["view"].organization_id
+ )
+ # Trim the stored side too: names created before this validation (or via the ORM) may carry
+ # surrounding whitespace and must still count as duplicates of their trimmed form.
+ duplicates = (
+ Project.objects.annotate(trimmed_name=Trim("name"))
+ .filter(organization_id=organization_id, trimmed_name__iexact=value)
+ .exclude(is_pending_deletion=True)
+ )
+ if self.instance is not None:
+ duplicates = duplicates.exclude(pk=self.instance.pk)
+ if duplicates.exists():
+ raise Conflict(
+ detail=f'There is already a project called "{value}" in this organization. Choose a different name.'
+ )
+ return value
+
def validate_access_control(self, value) -> None:
return TeamSerializer.validate_access_control(cast(TeamSerializer, self), value)
diff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.py
index fbdd90cedacf..b1e0ab81820d 100644
--- a/posthog/api/test/test_project.py
+++ b/posthog/api/test/test_project.py
@@ -47,6 +47,83 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore
"Only the project belonging to the scoped organization should be listed, the other one should be excluded",
)
+ @parameterized.expand(
+ [
+ ("exact_match", "Hedgebox"),
+ ("different_case", "HEDGEBOX"),
+ ("surrounding_whitespace", " Hedgebox "),
+ ]
+ )
+ def test_cannot_create_project_with_duplicate_name_in_same_organization(self, _name, duplicate_name):
+ self._set_unlimited_projects()
+ Project.objects.create_with_team(organization=self.organization, name="Hedgebox", initiating_user=self.user)
+
+ response = self.client.post("/api/projects/", {"name": duplicate_name})
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertIn("already a project called", response.json()["detail"])
+ self.assertEqual(Project.objects.filter(organization=self.organization, name__iexact="hedgebox").count(), 1)
+
+ def test_cannot_create_project_duplicating_a_stored_name_with_whitespace(self):
+ # The stored side is trimmed too: a legacy name saved with surrounding whitespace
+ # still blocks its clean form (and vice versa is covered by the parameterized test)
+ self._set_unlimited_projects()
+ Project.objects.create_with_team(organization=self.organization, name=" Hedgebox ", initiating_user=self.user)
+
+ response = self.client.post("/api/projects/", {"name": "Hedgebox"})
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertIn("already a project called", response.json()["detail"])
+
+ def test_can_create_project_with_same_name_as_project_in_another_organization(self):
+ self._set_unlimited_projects()
+ other_organization = Organization.objects.create(name="Other org")
+ Project.objects.create_with_team(organization=other_organization, name="Hedgebox", initiating_user=None)
+
+ response = self.client.post("/api/projects/", {"name": "Hedgebox"})
+
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response.json()["name"], "Hedgebox")
+
+ def test_creating_projects_without_name_generates_unique_default_names(self):
+ self._set_unlimited_projects()
+ # The fixture project already holds the plain default name
+ self.assertEqual(self.project.name, "Default project")
+
+ first_response = self.client.post("/api/projects/", {})
+ second_response = self.client.post("/api/projects/", {})
+
+ self.assertEqual(first_response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(second_response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(first_response.json()["name"], "Default project 2")
+ self.assertEqual(second_response.json()["name"], "Default project 3")
+
+ def test_cannot_rename_project_to_duplicate_name(self):
+ Project.objects.create_with_team(organization=self.organization, name="Hedgebox", initiating_user=self.user)
+
+ response = self.client.patch(f"/api/projects/{self.project.id}/", {"name": "hedgebox"})
+
+ self.assertEqual(response.status_code, status.HTTP_409_CONFLICT)
+ self.assertIn("already a project called", response.json()["detail"])
+ self.project.refresh_from_db()
+ self.assertEqual(self.project.name, "Default project")
+
+ def test_preexisting_projects_with_duplicate_names_can_still_be_updated(self):
+ # Duplicates created before the uniqueness rule must keep working, including saves that
+ # resubmit the unchanged name alongside other fields
+ duplicate_project, _ = Project.objects.create_with_team(
+ organization=self.organization, name=self.project.name, initiating_user=self.user
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{duplicate_project.id}/",
+ {"name": duplicate_project.name, "product_description": "still saveable"},
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ duplicate_project.refresh_from_db()
+ self.assertEqual(duplicate_project.product_description, "still saveable")
+
def test_cannot_create_second_demo_project(self):
# Create first demo project
Project.objects.create_with_team(
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index 13faa804736b..3b16421a1e77 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -443,7 +443,8 @@ def team_api_test_factory():
team_ids=[team_pk],
project_id=team_pk,
user_id=self.user.id,
- project_name="Default project",
+ # The org's first project already holds the plain default name, so the second one gets a suffix
+ project_name="Default project 2",
)
assert mock_capture.call_args_list == expected_capture_calls
diff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.py
index 618239aedd99..c4b9fe48bc06 100644
--- a/posthog/api/test/test_team_deletion.py
+++ b/posthog/api/test/test_team_deletion.py
@@ -86,7 +86,9 @@ class TestTeamDeletionSideEffects(NonAtomicBaseTest):
"detail": {
"changes": None,
"context": None,
- "name": "Default project",
+ # The org's first project holds the plain default name, so this team's
+ # implicit project got the suffixed one
+ "name": "Default project 2",
"short_id": None,
"trigger": None,
"type": None,
diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.py
index a5c78c3d24c2..f53d30f788ea 100644
--- a/posthog/api/test/test_team_project_differential.py
+++ b/posthog/api/test/test_team_project_differential.py
@@ -367,7 +367,11 @@ WRITE_ACTION_CASES = [
class TestWriteActionParity(DifferentialParityBase):
def _make_twin(self) -> tuple[Project, Team]:
- project, team = Project.objects.create_with_team(organization=self.organization, initiating_user=self.user)
+ # Twins share an explicit name so body comparisons don't diverge on the auto-suffixed
+ # default name; the manager deliberately allows same-name creation for legacy data.
+ project, team = Project.objects.create_with_team(
+ organization=self.organization, name="Twin project", initiating_user=self.user
+ )
return project, team
def _assert_team_shaped_parity(self, body_a: dict, body_b: dict) -> None:
@@ -437,7 +441,9 @@ class TestLifecycleMethodParity(DifferentialParityBase):
tests pin that unified behavior so a regression in the rewrite (or a re-divergence) fails loudly."""
def _make_twin(self) -> tuple[Project, Team]:
- project, team = Project.objects.create_with_team(organization=self.organization, initiating_user=self.user)
+ project, team = Project.objects.create_with_team(
+ organization=self.organization, name="Twin project", initiating_user=self.user
+ )
return project, team
def test_create_env_matches_project_via_rewrite(self):
@@ -449,8 +455,9 @@ class TestLifecycleMethodParity(DifferentialParityBase):
{"key": AvailableFeature.ORGANIZATIONS_PROJECTS, "name": "Projects", "limit": None}
]
self.organization.save()
+ # Distinct names: duplicate project names within an organization are rejected on create
env = self.client.post("/api/environments/", {"name": "x"}, format="json")
- proj = self.client.post("/api/projects/", {"name": "x"}, format="json")
+ proj = self.client.post("/api/projects/", {"name": "y"}, format="json")
self.assertEqual(env.status_code, status.HTTP_201_CREATED, env.json())
self.assertEqual(proj.status_code, status.HTTP_201_CREATED, proj.json())
diff --git a/posthog/management/commands/sync_feature_flags_from_api.py b/posthog/management/commands/sync_feature_flags_from_api.py
index c1f9fdfb98a1..4942cd9dbbb6 100644
--- a/posthog/management/commands/sync_feature_flags_from_api.py
+++ b/posthog/management/commands/sync_feature_flags_from_api.py
@@ -63,6 +63,10 @@ def sync_feature_flags_from_api(
return
for project in Project.objects.all():
+ team = project.teams.first()
+ if team is None:
+ output_fn(f"\nSkipping project {project.id} - {project.name or ''}: it has no teams")
+ continue
output_fn(f"\nProcessing project {project.id} - {project.name or ''}")
output_fn("=" * 50)
@@ -95,7 +99,7 @@ def sync_feature_flags_from_api(
elif flag_key not in existing_flags and is_enabled:
FeatureFlag.objects.create(
- team=project.teams.first(),
+ team=team,
name=flag_key,
key=flag_key,
created_by=first_user,
diff --git a/posthog/models/project.py b/posthog/models/project.py
index c9d674832d25..87c2461bdf46 100644
--- a/posthog/models/project.py
+++ b/posthog/models/project.py
@@ -1,5 +1,6 @@
from functools import cached_property
from typing import TYPE_CHECKING, Optional, cast
+from uuid import UUID
from django.core.validators import MinLengthValidator
from django.db import models, transaction
@@ -10,7 +11,35 @@ if TYPE_CHECKING:
from posthog.models import Team, User
-class ProjectManager(models.Manager):
+DEFAULT_PROJECT_NAME = "Default project"
+
+
+class ProjectManager(models.Manager["Project"]):
+ def get_unique_default_name(self, organization_id: "UUID | str") -> str:
+ """Return the default project name, suffixed with a number if already taken in the organization."""
+ taken = {
+ name.strip().lower()
+ for name in self.filter(
+ organization_id=organization_id, name__istartswith=DEFAULT_PROJECT_NAME
+ ).values_list("name", flat=True)
+ }
+ if DEFAULT_PROJECT_NAME.lower() not in taken:
+ return DEFAULT_PROJECT_NAME
+ suffix = 2
+ while f"{DEFAULT_PROJECT_NAME.lower()} {suffix}" in taken:
+ suffix += 1
+ return f"{DEFAULT_PROJECT_NAME} {suffix}"
+
+ def create(self, **kwargs) -> "Project":
+ # Without an explicit name the model default would produce ever more "Default project"
+ # duplicates in the org, so pick the first free numbered variant instead.
+ if not kwargs.get("name"):
+ kwargs.pop("name", None)
+ organization_id = kwargs.get("organization_id") or getattr(kwargs.get("organization"), "id", None)
+ if organization_id is not None:
+ kwargs["name"] = self.get_unique_default_name(organization_id)
+ return super().create(**kwargs)
+
def create_with_team(
self, *, team_fields: Optional[dict] = None, initiating_user: Optional["User"], **kwargs
) -> tuple["Project", "Team"]:
@@ -18,6 +47,11 @@ class ProjectManager(models.Manager):
if team_fields is None:
team_fields = {}
+ if not kwargs.get("name"):
+ kwargs.pop("name", None)
+ organization_id = kwargs.get("organization_id") or getattr(kwargs.get("organization"), "id", None)
+ if organization_id is not None:
+ kwargs["name"] = self.get_unique_default_name(organization_id)
if "name" in kwargs and "name" not in team_fields:
team_fields["name"] = kwargs["name"]
diff --git a/posthog/test/test_team.py b/posthog/test/test_team.py
index 67c39ca7ee36..7c6620fc8a28 100644
--- a/posthog/test/test_team.py
+++ b/posthog/test/test_team.py
@@ -221,7 +221,8 @@ class TestTeam(BaseTest):
project = Project.objects.filter(id=team.id).first()
assert project is not None
- self.assertEqual(project.name, "Default project")
+ # The fixture project already holds the plain default name, so this one gets a suffix
+ self.assertEqual(project.name, "Default project 2")
def test_each_team_gets_project_with_custom_name_and_same_id(self):
# Can be removed once environments are fully rolled out
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index cb22b06a920c..2bb87cff674e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54792,7 +54792,7 @@ export namespace Schemas {
readonly id?: number;
readonly organization?: string;
/**
- * Human-readable project name.
+ * Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.
* @minLength 1
* @maxLength 200
*/
@@ -58900,7 +58900,7 @@ export namespace Schemas {
readonly id: number;
readonly organization: string;
/**
- * Human-readable project name.
+ * Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.
* @minLength 1
* @maxLength 200
*/
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 4d66aafd1818..3fe456546848 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -103,7 +103,9 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zod
.min(1)
.max(organizationsProjectsPartialUpdateBodyNameMax)
.optional()
- .describe('Human-readable project name.'),
+ .describe(
+ 'Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.'
+ ),
product_description: zod
.string()
.max(organizationsProjectsPartialUpdateBodyProductDescriptionMax)
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index 77a8eb914d45..5050b790fed0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -3778,7 +3778,7 @@
},
"modifiers": {},
"name": {
- "description": "Human-readable project name.",
+ "description": "Project name. Must be unique within the organization (case-insensitive). If omitted on creation, a unique default name is generated.",
"maxLength": 200,
"minLength": 1,
"type": "string"