📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Allow creating projects with a website URL param at the same time
Blue Moused2b1e06dfb3e
diff --git a/backend/apps/cloud/src/project/dto/create-project.dto.ts b/backend/apps/cloud/src/project/dto/create-project.dto.tsindex 7436c0db6..2df7e2b81 100644--- a/backend/apps/cloud/src/project/dto/create-project.dto.ts+++ b/backend/apps/cloud/src/project/dto/create-project.dto.ts@@ -1,5 +1,12 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty, Length } from 'class-validator'+import {+ IsNotEmpty,+ IsOptional,+ IsUrl,+ Length,+ MaxLength,+ ValidateIf,+} from 'class-validator'import { ProjectOrganisationDto } from './project-organisation.dto'export class CreateProjectDTO extends ProjectOrganisationDto {@@ -46,4 +53,16 @@ export class CreateProjectDTO extends ProjectOrganisationDto {required: false,})countryBlacklist?: string[]++ @ApiProperty({+ example: 'https://example.com',+ required: false,+ description:+ 'Optional website URL. Used to display favicon and construct clickable page links.',+ })+ @IsOptional()+ @ValidateIf((o) => o.websiteUrl !== null && o.websiteUrl !== undefined)+ @IsUrl({}, { message: 'websiteUrl must be a valid URL' })+ @MaxLength(512)+ websiteUrl?: string | null}diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex ab2b12475..bf3ac11f4 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -375,6 +375,7 @@ export class ProjectController {const project = {id: pid,name: _trim(projectDTO.name),+ websiteUrl: projectDTO.websiteUrl ? _trim(projectDTO.websiteUrl) : null,origins: [],active: true,diff --git a/backend/apps/community/src/project/dto/create-project.dto.ts b/backend/apps/community/src/project/dto/create-project.dto.tsindex 3a307a676..37e97ca5f 100644--- a/backend/apps/community/src/project/dto/create-project.dto.ts+++ b/backend/apps/community/src/project/dto/create-project.dto.ts@@ -1,5 +1,11 @@import { ApiProperty } from '@nestjs/swagger'-import { IsNotEmpty, Length } from 'class-validator'+import {+ IsNotEmpty,+ IsOptional,+ IsUrl,+ Length,+ MaxLength,+} from 'class-validator'export class CreateProjectDTO {@ApiProperty({@@ -10,4 +16,15 @@ export class CreateProjectDTO {@IsNotEmpty()@Length(1, 50)name: string++ @ApiProperty({+ example: 'https://example.com',+ required: false,+ description:+ 'Optional website URL. Used to display favicon and construct clickable page links.',+ })+ @IsOptional()+ @IsUrl({}, { message: 'websiteUrl must be a valid URL' })+ @MaxLength(512)+ websiteUrl?: string | null}diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.tsindex b209c3e7a..d088cd974 100644--- a/backend/apps/community/src/project/project.controller.ts+++ b/backend/apps/community/src/project/project.controller.ts@@ -544,6 +544,9 @@ export class ProjectController {const project = new Project()project.id = pidproject.name = _trim(projectDTO.name)+ project.websiteUrl = projectDTO.websiteUrl+ ? _trim(projectDTO.websiteUrl)+ : nullawait createProjectClickhouse({ ...project, adminId: userId })diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsxindex 93a232a5d..7917c18c5 100644--- a/web/app/pages/Dashboard/Dashboard.tsx+++ b/web/app/pages/Dashboard/Dashboard.tsx@@ -1,6 +1,5 @@import cx from 'clsx'import _isEmpty from 'lodash/isEmpty'-import _keys from 'lodash/keys'import _map from 'lodash/map'import _size from 'lodash/size'import {@@ -45,9 +44,9 @@ import Input from '~/ui/Input'import LoadingBar from '~/ui/LoadingBar'import Modal from '~/ui/Modal'import Pagination from '~/ui/Pagination'-import Select from '~/ui/Select'import { Text } from '~/ui/Text'import { setCookie } from '~/utils/cookie'+import { isValidHttpUrl } from '~/utils/url'import { AddProject } from './AddProject'import { NoProjects } from './NoProjects'@@ -55,6 +54,7 @@ import { PeriodSelector } from './PeriodSelector'import { ProjectCard } from './ProjectCard'import { SortSelector, SORT_OPTIONS } from './SortSelector'import Button from '~/ui/Button'+import Select from '~/ui/Select'const PAGE_SIZE_OPTIONS = [12, 24, 48, 96]@@ -64,7 +64,34 @@ const DASHBOARD_VIEW = {} as constconst MAX_PROJECT_NAME_LENGTH = 50-const DEFAULT_PROJECT_NAME = 'Untitled Project'++interface NewProjectForm {+ name: string+ websiteUrl: string+ organisationId?: string+}++interface NewProjectErrors {+ name?: string+ websiteUrl?: string+}++interface NewProjectState {+ form: NewProjectForm+ errors: NewProjectErrors+ beenSubmitted: boolean+}++const DEFAULT_NEW_PROJECT_FORM: NewProjectForm = {+ name: '',+ websiteUrl: '',+}++const DEFAULT_NEW_PROJECT_STATE: NewProjectState = {+ form: DEFAULT_NEW_PROJECT_FORM,+ errors: {},+ beenSubmitted: false,+}const Dashboard = () => {const loaderData = useLoaderData<DashboardLoaderData>()@@ -130,14 +157,13 @@ const Dashboard = () => {: SORT_OPTIONS.ALPHA_ASC}, [searchParams])- // New project modal stateconst [newProjectModalOpen, setNewProjectModalOpen] = useState(false)- const [newProjectName, setNewProjectName] = useState('')- const [newProjectOrganisationId, setNewProjectOrganisationId] = useState<- string | undefined- >(undefined)- const [newProjectError, setNewProjectError] = useState<string | null>(null)- const [newProjectBeenSubmitted, setNewProjectBeenSubmitted] = useState(false)+ const [newProject, setNewProject] = useState(DEFAULT_NEW_PROJECT_STATE)+ const {+ form: newProjectForm,+ errors: newProjectErrors,+ beenSubmitted: newProjectBeenSubmitted,+ } = newProjectconst organisations = useMemo(() => [@@ -154,6 +180,11 @@ const Dashboard = () => {[user?.organisationMemberships, t],)+ const selectedNewProjectOrganisation = useMemo(+ () => organisations.find((org) => org.id === newProjectForm.organisationId),+ [organisations, newProjectForm.organisationId],+ )+const pageAmount = Math.ceil(paginationTotal / pageSize)// This search represents what's inside the search input@@ -204,57 +235,103 @@ const Dashboard = () => {setNewProjectModalOpen(true)}- const validateProjectName = () => {- const errors: { name?: string } = {}+ const updateNewProjectForm = <Field extends keyof NewProjectForm>(+ field: Field,+ value: NewProjectForm[Field],+ ) => {+ setNewProject((current) => {+ const form = {+ ...current.form,+ [field]: value,+ }++ if (field === 'organisationId') {+ return {+ ...current,+ form,+ }+ }++ const errors = { ...current.errors }+ delete errors[field as keyof NewProjectErrors]++ return {+ ...current,+ form,+ errors,+ }+ })+ }++ const getNewProjectErrors = (form: NewProjectForm) => {+ const errors: NewProjectErrors = {}+ const name = form.name.trim()+ const websiteUrl = form.websiteUrl.trim()- if (_isEmpty(newProjectName)) {+ if (_isEmpty(name)) {errors.name = t('project.settings.noNameError')}- if (_size(newProjectName) > MAX_PROJECT_NAME_LENGTH) {+ if (_size(name) > MAX_PROJECT_NAME_LENGTH) {errors.name = t('project.settings.pxCharsError', {amount: MAX_PROJECT_NAME_LENGTH,})}- return { errors, valid: _isEmpty(_keys(errors)) }+ if (websiteUrl && !isValidHttpUrl(websiteUrl)) {+ errors.websiteUrl = t('project.settings.invalidUrl')+ }++ return errors}// Handle fetcher responses for create projectuseEffect(() => {- if (fetcher.data?.success && fetcher.data?.intent === 'create-project') {+ const data = fetcher.data++ if (data?.success && data.intent === 'create-project') {refetchProjects()toast.success(t('project.settings.created'))closeNewProjectModal()- } else if (- fetcher.data?.error &&- fetcher.data?.intent === 'create-project'- ) {- setNewProjectError(fetcher.data.error)- toast.error(fetcher.data.error)- } else if (- fetcher.data?.fieldErrors?.name &&- fetcher.data?.intent === 'create-project'- ) {- setNewProjectError(fetcher.data.fieldErrors.name)+ } else if (data?.error && data.intent === 'create-project') {+ setNewProject((current) => ({+ ...current,+ errors: {+ ...current.errors,+ name: data.error,+ },+ }))+ toast.error(data.error)+ } else if (data?.fieldErrors && data.intent === 'create-project') {+ setNewProject((current) => ({+ ...current,+ errors: {+ ...current.errors,+ ...data.fieldErrors,+ },+ }))}}, [fetcher.data, t]) // eslint-disable-line react-hooks/exhaustive-depsconst isNewProjectLoading = fetcher.state === 'submitting'const onCreateProject = () => {- setNewProjectBeenSubmitted(true)- const { errors, valid } = validateProjectName()+ const errors = getNewProjectErrors(newProjectForm)++ setNewProject((current) => ({+ ...current,+ beenSubmitted: true,+ errors,+ }))- if (!valid) {- setNewProjectError(errors.name || null)+ if (!_isEmpty(errors)) {return}if (!isSelfhosted &&user?.planCode === 'none' &&- !newProjectOrganisationId+ !newProjectForm.organisationId) {toast.error(t('project.settings.subscriptionRequired'))return@@ -262,9 +339,12 @@ const Dashboard = () => {const formData = new FormData()formData.set('intent', 'create-project')- formData.set('name', newProjectName || DEFAULT_PROJECT_NAME)- if (newProjectOrganisationId) {- formData.set('organisationId', newProjectOrganisationId)+ formData.set('name', newProjectForm.name.trim())+ if (newProjectForm.websiteUrl.trim()) {+ formData.set('websiteUrl', newProjectForm.websiteUrl.trim())+ }+ if (newProjectForm.organisationId) {+ formData.set('organisationId', newProjectForm.organisationId)}fetcher.submit(formData, { method: 'post' })}@@ -275,10 +355,7 @@ const Dashboard = () => {}setNewProjectModalOpen(false)- setNewProjectError(null)- setNewProjectName('')- setNewProjectOrganisationId(undefined)- setNewProjectBeenSubmitted(false)+ setNewProject(DEFAULT_NEW_PROJECT_STATE)}const refetchProjects = useCallback(() => {@@ -530,11 +607,24 @@ const Dashboard = () => {<Inputname='project-name-input'label={t('project.settings.name')}- hint={t('project.settings.nameHint')}- value={newProjectName}+ value={newProjectForm.name}placeholder='My awesome website'- onChange={(e) => setNewProjectName(e.target.value)}- error={newProjectBeenSubmitted ? newProjectError : null}+ onChange={(e) => updateNewProjectForm('name', e.target.value)}+ error={newProjectBeenSubmitted ? newProjectErrors.name : null}+ />+ <Input+ name='websiteUrl'+ label={t('project.settings.websiteUrl')}+ hint={t('project.settings.websiteUrlHint')}+ value={newProjectForm.websiteUrl}+ placeholder={t('project.settings.websiteUrlPlaceholder')}+ className='mt-4'+ onChange={(e) =>+ updateNewProjectForm('websiteUrl', e.target.value)+ }+ error={+ newProjectBeenSubmitted ? newProjectErrors.websiteUrl : null+ }/>{organisations.length > 1 ? (<div className='mt-4'>@@ -551,29 +641,20 @@ const Dashboard = () => {return item.name}}onSelect={(item) => {- setNewProjectOrganisationId(item.id)+ updateNewProjectForm('organisationId', item.id)}}label={t('project.settings.organisation')}hint={t('project.settings.organisationHint')}- title={- organisations.find(- (org) => org.id === newProjectOrganisationId,- )?.name- }- selectedItem={organisations.find(- (org) => org.id === newProjectOrganisationId,- )}+ title={selectedNewProjectOrganisation?.name}+ selectedItem={selectedNewProjectOrganisation}/></div>) : null}- <Text as='p' size='sm' colour='muted' className='mt-2 italic'>- {t('project.settings.createHint')}- </Text></div>}title={t('project.settings.create')}isOpened={newProjectModalOpen}- submitDisabled={!newProjectName}+ submitDisabled={!newProjectForm.name.trim()}/></>)diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex f0f488911..78f6a8145 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -58,6 +58,7 @@ import { Text } from '~/ui/Text'// Select is used inside tab componentsimport countries from '~/utils/isoCountries'import routes from '~/utils/routes'+import { isValidHttpUrl } from '~/utils/url'import CCRow from '../View/components/CCRow'@@ -1020,15 +1021,8 @@ const ProjectSettings = () => {})}- if (data.websiteUrl && data.websiteUrl.trim()) {- try {- const url = new URL(data.websiteUrl.trim())- if (!['http:', 'https:'].includes(url.protocol)) {- allErrors.websiteUrl = t('project.settings.invalidUrl')- }- } catch {- allErrors.websiteUrl = t('project.settings.invalidUrl')- }+ if (data.websiteUrl?.trim() && !isValidHttpUrl(data.websiteUrl)) {+ allErrors.websiteUrl = t('project.settings.invalidUrl')}return allErrorsdiff --git a/web/app/routes/dashboard.tsx b/web/app/routes/dashboard.tsxindex ee2b3d436..c65e7a38d 100644--- a/web/app/routes/dashboard.tsx+++ b/web/app/routes/dashboard.tsx@@ -16,6 +16,10 @@ import {redirectIfNotAuthenticated,createHeadersWithCookies,} from '~/utils/session.server'+import { isValidHttpUrl } from '~/utils/url'++const INVALID_WEBSITE_URL_ERROR =+ 'Please enter a valid URL (e.g., https://example.com)'export const meta: MetaFunction = () => {// eslint-disable-next-line react-hooks/rules-of-hooks@@ -49,6 +53,7 @@ export interface DashboardActionData {error?: stringfieldErrors?: {name?: string+ websiteUrl?: string}project?: ProjectisPinned?: boolean@@ -63,28 +68,38 @@ export async function action({ request }: ActionFunctionArgs) {switch (intent) {case 'create-project': {const name = formData.get('name')?.toString() || ''+ const trimmedName = name.trim()+ const websiteUrl = formData.get('websiteUrl')?.toString().trim()const organisationId = formData.get('organisationId')?.toString()+ const fieldErrors: DashboardActionData['fieldErrors'] = {}- if (!name.trim()) {- return data<DashboardActionData>(- { intent, fieldErrors: { name: 'Project name is required' } },- { status: 400 },- )+ if (!trimmedName) {+ fieldErrors.name = 'Project name is required'+ }++ if (trimmedName.length > 50) {+ fieldErrors.name = 'Project name must be 50 characters or less'+ }++ if (websiteUrl && !isValidHttpUrl(websiteUrl)) {+ fieldErrors.websiteUrl = INVALID_WEBSITE_URL_ERROR}- if (name.length > 50) {+ if (fieldErrors.name || fieldErrors.websiteUrl) {return data<DashboardActionData>(- {- intent,- fieldErrors: { name: 'Project name must be 50 characters or less' },- },+ { intent, fieldErrors },{ status: 400 },)}- const body: { name: string; organisationId?: string } = {- name: name.trim(),+ const body: {+ name: string+ websiteUrl?: string+ organisationId?: string+ } = {+ name: trimmedName,}+ if (websiteUrl) body.websiteUrl = websiteUrlif (organisationId) body.organisationId = organisationIdconst result = await serverFetch<Project>(request, 'project', {diff --git a/web/app/utils/url.ts b/web/app/utils/url.tsnew file mode 100644index 000000000..db4fc2b5c--- /dev/null+++ b/web/app/utils/url.ts@@ -0,0 +1,8 @@+export const isValidHttpUrl = (value: string) => {+ try {+ const url = new URL(value.trim())+ return ['http:', 'https:'].includes(url.protocol)+ } catch {+ return false+ }+}diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 7370504b7..a79cc5e71 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -2444,39 +2444,39 @@"publicHint": "If enabled, anyone on the Internet would be able to see this project's dashboard.\nOnly the project administrator can edit the settings.","delete": "Delete project","reset": "Reset project",- "qDelete": "Delete the project?",- "qReset": "Reset the project?",- "deleteHint": "By pressing 'Delete project' you understand, that this action is irreversible.\nThe project and all the data related to it will be deleted from our servers.",- "resetHint": "By pressing 'Reset project' you understand, that this action is irreversible.\nThe project's pageviews and custom events will be removed from our servers, but the project identifier and other configuration will be retained.",- "deleted": "The project has been deleted",- "projectReset": "The project has been reset",- "noPeople": "No people have been added to this project yet.",+ "qDelete": "Delete this project?",+ "qReset": "Reset this project?",+ "deleteHint": "Deleting this project is permanent. We will delete the project and all related data from our servers. No project data will be kept, and this cannot be undone.",+ "resetHint": "Resetting this project is permanent. We will delete its pageviews and custom events from our servers. The project ID and settings will be kept.",+ "deleted": "Project deleted",+ "projectReset": "Project reset",+ "noPeople": "No members have been added to this project yet.","removeMember": "Remove member",- "removeConfirm": "Are you sure you want to stop sharing your project with this user?",- "removeReportConfirm": "Are you sure you want to stop sending project reports to this user?",+ "removeConfirm": "Remove this member from the project? They will lose access, but project data will stay unchanged.",+ "removeReportConfirm": "Stop sending reports to this recipient? They will no longer receive scheduled project reports.","removeUser": "Remove {{user}}?",- "people": "People",- "inviteCoworkers": "Invite your coworkers",- "peopleEmptyTitle": "No project members yet",- "peopleEmptyDescription": "Invite teammates to share this project's analytics and manage their access with roles.",- "addARecipient": "Add a recipient",- "addARecipientDesc": "Enter an email address of the person you want to send reports to. They don't necessarily need to have an account on Swetrix.\nWe will send them your site's reports on a regular basis.",- "invite": "Invite a user",- "inviteTo": "Invite a user to {{project}}",- "inviteDesc": "Enter an email address and a role of the person you want to share your project with.\nWe shall contact them over email to offer the access to the project, and they will see the invitation in their dashboard as well.",- "inviteDescSelfhosted": "Enter an email address and a role of the person you want to share your project with.\nThey will see the invitation in their dashboard.",- "inviteExpity": "The invitation will expire in {{amount}} hours.",+ "people": "Members",+ "inviteCoworkers": "Invite teammates",+ "peopleEmptyTitle": "No members yet",+ "peopleEmptyDescription": "Invite teammates to view this project's analytics and manage their access by role.",+ "addARecipient": "Add recipient",+ "addARecipientDesc": "Enter the email address that should receive reports. The recipient does not need a Swetrix account. We will send them scheduled reports for this site.",+ "invite": "Invite user",+ "inviteTo": "Invite user to {{project}}",+ "inviteDesc": "Enter the person's email address and role. We will email them an invitation, and it will also appear in their Swetrix dashboard.",+ "inviteDescSelfhosted": "Enter the person's email address and role. The invitation will appear in their dashboard.",+ "inviteExpity": "This invitation expires in {{amount}} hours.","role": "Role","roles": {"admin": {- "name": "Administrator",- "desc": "Can manage the project's settings, add/remove members, and invite new users.",+ "name": "Admin",+ "desc": "Can manage project settings, members, invites, and access.","shortDesc": "Can manage the project"},"viewer": {"name": "Viewer",- "desc": "Has a read-only access to the project.",- "shortDesc": "Can only view the project"+ "desc": "Can view the project, but cannot change settings or access.",+ "shortDesc": "Can view only"}},"errorNoRole": "Please select a role.",