Skip to content

๐Ÿ“ˆ 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!

feat: Google Search Console integration

Blue Mouseb4f66aeb83fb
diff --git a/backend/.env.example b/backend/.env.example
index 4acd54a32..99a3bb636 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -58,7 +58,7 @@ CDN_ACCESS_TOKEN=SOME_SECRET_TOKEN
# Captcha API
CAPTCHA_SALT=
-# Google SSO
+# Google SSO & GSC integration
GOOGLE_OAUTH2_CLIENT_ID=
GOOGLE_OAUTH2_CLIENT_SECRET=
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index f350e39cb..33c26813d 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -91,6 +91,8 @@ import { GetOverallStatsDto } from './dto/get-overall-stats.dto'
import { NoscriptDto } from './dto/noscript.dto'
import { LiveVisitorsDto } from './dto/live-visitors.dto'
import { GetHeartbeatStatsDto } from './dto/get-heartbeat-stats'
+import { GetKeywordsDto } from './dto/get-keywords.dto'
+import { GSCService } from '../project/gsc.service'
dayjs.extend(utc)
dayjs.extend(dayjsTimezone)
@@ -195,6 +197,7 @@ export class AnalyticsController {
constructor(
private readonly analyticsService: AnalyticsService,
private readonly logger: AppLoggerService,
+ private readonly gscService: GSCService,
) {}
@ApiBearerAuth()
@@ -766,6 +769,48 @@ export class AnalyticsController {
return { ...flow, appliedFilters }
}
+ @Get('keywords')
+ @Auth(true, true)
+ async getKeywords(
+ @Query() data: GetKeywordsDto,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, period, from, to, timezone = DEFAULT_TIMEZONE } = data
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+
+ diff = res.diff
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ null,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ const keywords = await this.gscService.getKeywords(pid, groupFrom, groupTo)
+ return { keywords }
+ }
+
@Get('birdseye')
@Auth(true, true)
// returns overall short statistics per project
diff --git a/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts b/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts
new file mode 100644
index 000000000..d39e40b75
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts
@@ -0,0 +1,21 @@
+import { IsOptional, IsString } from 'class-validator'
+
+export class GetKeywordsDto {
+ @IsString()
+ pid: string
+
+ @IsString()
+ period: string
+
+ @IsOptional()
+ @IsString()
+ from?: string
+
+ @IsOptional()
+ @IsString()
+ to?: string
+
+ @IsOptional()
+ @IsString()
+ timezone?: string
+}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index 47b7b217e..e1f531fc6 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -134,4 +134,20 @@ export class Project {
@ManyToOne(() => Organisation, org => org.projects, { nullable: true })
organisation: Organisation | null
+
+ // Google Search Console integration
+ @Column('varchar', { nullable: true, default: null, length: 512 })
+ gscPropertyUri: string | null
+
+ @Column('text', { nullable: true, default: null })
+ gscAccessTokenEnc: string | null
+
+ @Column('text', { nullable: true, default: null })
+ gscRefreshTokenEnc: string | null
+
+ @Column('bigint', { nullable: true, default: null })
+ gscTokenExpiry: string | null
+
+ @Column('varchar', { nullable: true, default: null, length: 512 })
+ gscScope: string | null
}
diff --git a/backend/apps/cloud/src/project/gsc.controller.ts b/backend/apps/cloud/src/project/gsc.controller.ts
new file mode 100644
index 000000000..a5f0fbab0
--- /dev/null
+++ b/backend/apps/cloud/src/project/gsc.controller.ts
@@ -0,0 +1,97 @@
+import {
+ Controller,
+ Post,
+ Get,
+ Delete,
+ Param,
+ Body,
+ Query,
+ UseGuards,
+ BadRequestException,
+ HttpCode,
+ Response,
+} from '@nestjs/common'
+import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
+
+import { AuthenticationGuard } from '../auth/guards/authentication.guard'
+import { Auth } from '../auth/decorators'
+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
+import { GSCService } from './gsc.service'
+import { ProjectService } from './project.service'
+
+@ApiTags('Project - Google Search Console')
+@UseGuards(AuthenticationGuard)
+@Controller({ path: 'project', version: '1' })
+export class GSCController {
+ constructor(
+ private readonly gscService: GSCService,
+ private readonly projectService: ProjectService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Post(':pid/gsc/connect')
+ @Auth()
+ async connect(@Param('pid') pid: string, @CurrentUserId() uid: string) {
+ // ensure user can manage project
+ const project = await this.projectService.getRedisProject(pid)
+ this.projectService.allowedToManage(project, uid)
+ return this.gscService.generateConnectURL(uid, pid)
+ }
+
+ // OAuth2 callback endpoint
+ @Get('gsc/callback')
+ async oauthCallback(
+ @Query('code') code: string,
+ @Query('state') state: string,
+ @Response() res: any,
+ ) {
+ if (!code || !state) {
+ throw new BadRequestException('Invalid OAuth callback parameters')
+ }
+ const { pid } = await this.gscService.handleOAuthCallback(code, state)
+ res.redirect(`/project/${pid}/settings?gsc=connected`)
+ }
+
+ @ApiBearerAuth()
+ @Get(':pid/gsc/status')
+ @Auth()
+ async status(@Param('pid') pid: string, @CurrentUserId() uid: string) {
+ const project = await this.projectService.getRedisProject(pid)
+ this.projectService.allowedToManage(project, uid)
+ const connected = await this.gscService.isConnected(pid)
+ return { connected }
+ }
+
+ @ApiBearerAuth()
+ @Get(':pid/gsc/properties')
+ @Auth()
+ async properties(@Param('pid') pid: string, @CurrentUserId() uid: string) {
+ const project = await this.projectService.getRedisProject(pid)
+ this.projectService.allowedToManage(project, uid)
+ return this.gscService.listSites(pid)
+ }
+
+ @ApiBearerAuth()
+ @Post(':pid/gsc/property')
+ @Auth()
+ async setProperty(
+ @Param('pid') pid: string,
+ @CurrentUserId() uid: string,
+ @Body() body: { propertyUri: string },
+ ) {
+ const project = await this.projectService.getRedisProject(pid)
+ this.projectService.allowedToManage(project, uid)
+ await this.gscService.setProperty(pid, body?.propertyUri)
+ return {}
+ }
+
+ @ApiBearerAuth()
+ @Delete(':pid/gsc')
+ @Auth()
+ @HttpCode(204)
+ async disconnect(@Param('pid') pid: string, @CurrentUserId() uid: string) {
+ const project = await this.projectService.getRedisProject(pid)
+ this.projectService.allowedToManage(project, uid)
+ await this.gscService.disconnect(pid)
+ }
+}
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
new file mode 100644
index 000000000..774844a94
--- /dev/null
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -0,0 +1,281 @@
+import _isEmpty from 'lodash/isEmpty'
+import dayjs from 'dayjs'
+import {
+ Injectable,
+ BadRequestException,
+ InternalServerErrorException,
+} from '@nestjs/common'
+import { ConfigService } from '@nestjs/config'
+import { google } from 'googleapis'
+import CryptoJS from 'crypto-js'
+
+import { EMAIL_ACTION_ENCRYPTION_KEY, redis } from '../common/constants'
+import { ProjectService } from './project.service'
+
+type StoredTokens = {
+ access_token?: string
+ refresh_token?: string
+ scope?: string
+ expiry_date?: number
+ property_uri?: string | null
+}
+
+const REDIS_STATE_PREFIX = 'gsc:state:'
+// tokens are stored in DB; Redis is used only for short-lived OAuth state
+
+@Injectable()
+export class GSCService {
+ constructor(
+ private readonly configService: ConfigService,
+ private readonly projectService: ProjectService,
+ ) {}
+
+ private getRedirectUri(): string {
+ const override = this.configService.get<string>(
+ 'GOOGLE_OAUTH2_GSC_REDIRECT_URL',
+ )
+ if (override) return override
+
+ const origin =
+ this.configService.get<string>('PRODUCTION_ORIGIN') ||
+ 'http://localhost:5005'
+ // Nest versioned path - /v1/project/gsc/callback
+ return `${origin.replace(/\/$/, '')}/v1/project/gsc/callback`
+ }
+
+ private getOAuthClient() {
+ const clientId = this.configService.get<string>('GOOGLE_OAUTH2_CLIENT_ID')
+ const clientSecret = this.configService.get<string>(
+ 'GOOGLE_OAUTH2_CLIENT_SECRET',
+ )
+
+ if (!clientId || !clientSecret) {
+ throw new InternalServerErrorException('Google OAuth2 is not configured')
+ }
+
+ return new google.auth.OAuth2(clientId, clientSecret, this.getRedirectUri())
+ }
+
+ async generateConnectURL(uid: string, pid: string): Promise<{ url: string }> {
+ const oauth2Client = this.getOAuthClient()
+
+ const state = `${pid}:${uid}:${Date.now()}`
+ await redis.set(
+ REDIS_STATE_PREFIX + state,
+ JSON.stringify({ uid, pid }),
+ 'EX',
+ 600,
+ )
+
+ const url = oauth2Client.generateAuthUrl({
+ access_type: 'offline',
+ scope: ['https://www.googleapis.com/auth/webmasters.readonly'],
+ prompt: 'consent',
+ state,
+ })
+
+ return { url }
+ }
+
+ async handleOAuthCallback(code: string, state: string) {
+ const cached = await redis.get(REDIS_STATE_PREFIX + state)
+ if (!cached) {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
+ const { pid } = JSON.parse(cached)
+
+ const oauth2Client = this.getOAuthClient()
+ const { tokens } = await oauth2Client.getToken(code)
+
+ const toStore: StoredTokens = {
+ access_token: tokens.access_token,
+ refresh_token: tokens.refresh_token,
+ expiry_date: tokens.expiry_date,
+ scope: tokens.scope,
+ // preserve previously selected property if any
+ ...(await this.getStoredTokens(pid)),
+ }
+
+ await this.setStoredTokens(pid, toStore)
+
+ // One-time state
+ await redis.del(REDIS_STATE_PREFIX + state)
+
+ return { pid }
+ }
+
+ private async getStoredTokens(pid: string): Promise<StoredTokens> {
+ const project = await this.projectService.findOne({
+ where: { id: pid },
+ select: [
+ 'gscAccessTokenEnc',
+ 'gscRefreshTokenEnc',
+ 'gscTokenExpiry',
+ 'gscScope',
+ 'gscPropertyUri',
+ ],
+ })
+
+ if (!project) return {}
+
+ const decrypt = (val?: string | null) => {
+ if (!val) return undefined
+ try {
+ const bytes = CryptoJS.Rabbit.decrypt(val, EMAIL_ACTION_ENCRYPTION_KEY)
+ return bytes.toString(CryptoJS.enc.Utf8) || undefined
+ } catch {
+ return undefined
+ }
+ }
+
+ const expiry = project.gscTokenExpiry
+ ? Number(project.gscTokenExpiry)
+ : undefined
+
+ return {
+ access_token: decrypt(project.gscAccessTokenEnc),
+ refresh_token: decrypt(project.gscRefreshTokenEnc),
+ expiry_date: expiry,
+ scope: project.gscScope || undefined,
+ property_uri: project.gscPropertyUri || null,
+ }
+ }
+
+ private async setStoredTokens(pid: string, tokens: StoredTokens) {
+ const encrypt = (val?: string) =>
+ val
+ ? CryptoJS.Rabbit.encrypt(val, EMAIL_ACTION_ENCRYPTION_KEY).toString()
+ : null
+
+ await this.projectService.update({ id: pid }, {
+ gscAccessTokenEnc: encrypt(tokens.access_token),
+ gscRefreshTokenEnc: encrypt(tokens.refresh_token),
+ gscTokenExpiry: tokens.expiry_date as any,
+ gscScope: tokens.scope || null,
+ gscPropertyUri: tokens.property_uri ?? null,
+ } as any)
+ }
+
+ async disconnect(pid: string) {
+ await this.projectService.update({ id: pid }, {
+ gscAccessTokenEnc: null,
+ gscRefreshTokenEnc: null,
+ gscTokenExpiry: null,
+ gscScope: null,
+ gscPropertyUri: null,
+ } as any)
+ }
+
+ async isConnected(pid: string) {
+ const tokens = await this.getStoredTokens(pid)
+ return !_isEmpty(tokens?.refresh_token || tokens?.access_token)
+ }
+
+ private async getAuthedClientForPid(pid: string) {
+ const tokens = await this.getStoredTokens(pid)
+ if (_isEmpty(tokens)) {
+ throw new BadRequestException(
+ 'Search Console is not connected for this project',
+ )
+ }
+ const oauth2Client = this.getOAuthClient()
+ oauth2Client.setCredentials(tokens)
+
+ // Refresh if expired
+ if (tokens.expiry_date && tokens.expiry_date <= Date.now()) {
+ const refreshed = await oauth2Client.getAccessToken()
+ const newAccess =
+ typeof refreshed === 'string' ? refreshed : refreshed?.token
+ if (newAccess) {
+ const updated: StoredTokens = {
+ ...tokens,
+ access_token: newAccess,
+ expiry_date: Date.now() + 55 * 60 * 1000,
+ }
+ await this.setStoredTokens(pid, updated)
+ oauth2Client.setCredentials({ ...updated })
+ }
+ }
+
+ return oauth2Client
+ }
+
+ async listSites(
+ pid: string,
+ ): Promise<{ siteUrl: string; permissionLevel?: string }[]> {
+ const auth = await this.getAuthedClientForPid(pid)
+ const sc = google.searchconsole({ version: 'v1', auth })
+ try {
+ const { data } = await sc.sites.list({})
+ // @ts-ignore
+ const sites = (data?.siteEntry || data?.siteEntries || []) as any[]
+ return sites.map((s: any) => ({
+ siteUrl: s.siteUrl,
+ permissionLevel: s.permissionLevel,
+ }))
+ } catch {
+ throw new InternalServerErrorException(
+ 'Failed to fetch Search Console sites',
+ )
+ }
+ }
+
+ async setProperty(pid: string, propertyUri: string) {
+ const tokens = await this.getStoredTokens(pid)
+ if (_isEmpty(tokens)) {
+ throw new BadRequestException(
+ 'Search Console is not connected for this project',
+ )
+ }
+ await this.setStoredTokens(pid, { ...tokens, property_uri: propertyUri })
+ }
+
+ async getKeywords(
+ pid: string,
+ from: string,
+ to: string,
+ ): Promise<{ name: string; count: number }[]> {
+ const tokens = await this.getStoredTokens(pid)
+ if (_isEmpty(tokens) || _isEmpty(tokens.property_uri)) {
+ throw new BadRequestException(
+ 'Search Console property is not linked for this project',
+ )
+ }
+
+ const auth = await this.getAuthedClientForPid(pid)
+ const sc = google.searchconsole({ version: 'v1', auth })
+
+ // Dates must be YYYY-MM-DD
+ const startDate = dayjs(from).format('YYYY-MM-DD')
+ const endDate = dayjs(to).format('YYYY-MM-DD')
+
+ try {
+ const { data } = await sc.searchanalytics.query({
+ siteUrl: tokens.property_uri as string,
+ requestBody: {
+ startDate,
+ endDate,
+ dimensions: ['query'],
+ rowLimit: 250, // enough for UI panel
+ dataState: 'final',
+ },
+ })
+
+ const rows = (data.rows || []) as Array<{
+ keys: string[]
+ clicks?: number
+ }>
+ return rows
+ .map(row => ({
+ name: row.keys?.[0] || '(not set)',
+ count: Math.round(row.clicks || 0),
+ }))
+ .filter(Boolean)
+ } catch {
+ throw new InternalServerErrorException(
+ 'Failed to fetch keywords from Search Console',
+ )
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.ts
index bb827e70a..8b2495359 100644
--- a/backend/apps/cloud/src/project/project.module.ts
+++ b/backend/apps/cloud/src/project/project.module.ts
@@ -3,6 +3,8 @@ import { TypeOrmModule } from '@nestjs/typeorm'
import { ProjectService } from './project.service'
import { ProjectController } from './project.controller'
+import { GSCController } from './gsc.controller'
+import { GSCService } from './gsc.service'
import { UserModule } from '../user/user.module'
import { ActionTokensModule } from '../action-tokens/action-tokens.module'
import { MailerModule } from '../mailer/mailer.module'
@@ -30,8 +32,18 @@ import { ProjectExtraService } from './project-extra.service'
ActionTokensModule,
MailerModule,
],
- providers: [ProjectService, ProjectExtraService, ProjectsViewsRepository],
- exports: [ProjectService, ProjectExtraService, ProjectsViewsRepository],
- controllers: [ProjectController],
+ providers: [
+ ProjectService,
+ ProjectExtraService,
+ ProjectsViewsRepository,
+ GSCService,
+ ],
+ exports: [
+ ProjectService,
+ ProjectExtraService,
+ ProjectsViewsRepository,
+ GSCService,
+ ],
+ controllers: [ProjectController, GSCController],
})
export class ProjectModule {}
diff --git a/backend/migrations/mysql/2025_10_29.sql b/backend/migrations/mysql/2025_10_29.sql
new file mode 100644
index 000000000..7bcb8038f
--- /dev/null
+++ b/backend/migrations/mysql/2025_10_29.sql
@@ -0,0 +1,6 @@
+ALTER TABLE project
+ ADD COLUMN `gscPropertyUri` varchar(512) DEFAULT NULL AFTER `organisationId`,
+ ADD COLUMN `gscAccessTokenEnc` text DEFAULT NULL AFTER `gscPropertyUri`,
+ ADD COLUMN `gscRefreshTokenEnc` text DEFAULT NULL AFTER `gscAccessTokenEnc`,
+ ADD COLUMN `gscTokenExpiry` bigint DEFAULT NULL AFTER `gscRefreshTokenEnc`,
+ ADD COLUMN `gscScope` varchar(512) DEFAULT NULL AFTER `gscTokenExpiry`;
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 09dcfb47b..aa319d82b 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1514,3 +1514,61 @@ export const completeOnboarding = () =>
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+
+// Google Search Console integration
+export const generateGSCAuthURL = (pid: string) =>
+ api
+ .post(`project/${pid}/gsc/connect`)
+ .then((response): { url: string } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const getGSCStatus = (pid: string) =>
+ api
+ .get(`project/${pid}/gsc/status`)
+ .then((response): { connected: boolean } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const getGSCProperties = (pid: string) =>
+ api
+ .get(`project/${pid}/gsc/properties`)
+ .then((response): { siteUrl: string; permissionLevel?: string }[] => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const setGSCProperty = (pid: string, propertyUri: string) =>
+ api
+ .post(`project/${pid}/gsc/property`, { propertyUri })
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const disconnectGSC = (pid: string) =>
+ api
+ .delete(`project/${pid}/gsc`)
+ .then((response) => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
+
+export const getGSCKeywords = (
+ pid: string,
+ period = '3d',
+ from = '',
+ to = '',
+ timezone = '',
+ password: string | undefined = '',
+) =>
+ api
+ .get(`log/keywords?pid=${pid}&period=${period}&from=${from}&to=${to}&timezone=${timezone}`, {
+ headers: { 'x-password': password },
+ })
+ .then((response): { keywords: { name: string; count: number }[] } => response.data)
+ .catch((error) => {
+ throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
+ })
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index 2b12820af..85bd087a4 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -21,7 +21,7 @@ import {
ChevronLeftIcon,
} from 'lucide-react'
import React, { useState, useEffect, useMemo, useCallback } from 'react'
-import { useTranslation } from 'react-i18next'
+import { Trans, useTranslation } from 'react-i18next'
import { useLoaderData, useNavigate, Link } from 'react-router'
import { toast } from 'sonner'
@@ -35,6 +35,11 @@ import {
resetFilters,
getProject,
assignProjectToOrganisation,
+ generateGSCAuthURL,
+ getGSCStatus,
+ getGSCProperties,
+ setGSCProperty,
+ disconnectGSC,
} from '~/api'
import { withAuthentication, auth } from '~/hoc/protected'
import { useRequiredParams } from '~/hooks/useRequiredParams'
@@ -44,6 +49,8 @@ import { useAuth } from '~/providers/AuthProvider'
import Button from '~/ui/Button'
import DatePicker from '~/ui/Datepicker'
import Dropdown from '~/ui/Dropdown'
+import GoogleGSVG from '~/ui/icons/GoogleG'
+import GoogleSearchConsoleSVG from '~/ui/icons/GoogleSearchConsole'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
import Modal from '~/ui/Modal'
@@ -302,9 +309,14 @@ const ProjectSettings = () => {
const [isLoading, setIsLoading] = useState<boolean | null>(null)
const [error, setError] = useState<string | null>(null)
- const [activeTab, setActiveTab] = useState<'general' | 'shields' | 'access' | 'emails' | 'people' | 'danger'>(
- 'general',
- )
+ const [activeTab, setActiveTab] = useState<
+ 'general' | 'shields' | 'access' | 'integrations' | 'emails' | 'people' | 'danger'
+ >('general')
+
+ // Google Search Console integration state
+ const [gscConnected, setGscConnected] = useState<boolean | null>(null)
+ const [gscProperties, setGscProperties] = useState<{ siteUrl: string; permissionLevel?: string }[]>([])
+ const [gscProperty, setGscProperty] = useState<string>('')
// for reset data via filters
const [activeFilter, setActiveFilter] = useState<string[]>([])
@@ -372,6 +384,29 @@ const ProjectSettings = () => {
}
}
+ const refreshGSCStatus = useCallback(async () => {
+ try {
+ const { connected } = await getGSCStatus(id)
+ setGscConnected(connected)
+ if (connected) {
+ try {
+ const props = await getGSCProperties(id)
+ setGscProperties(props)
+ } catch {
+ //
+ }
+ } else {
+ setGscProperties([])
+ }
+ } catch {
+ setGscConnected(false)
+ }
+ }, [id])
+
+ useEffect(() => {
+ refreshGSCStatus()
+ }, [refreshGSCStatus])
+
useEffect(() => {
if (authLoading) {
return
@@ -579,6 +614,7 @@ const ProjectSettings = () => {
{ id: 'general', label: t('project.settings.tabs.general'), icon: Settings2Icon, visible: true },
{ id: 'access', label: t('project.settings.tabs.access'), icon: LockIcon, visible: true },
{ id: 'shields', label: t('project.settings.tabs.shields'), icon: ShieldIcon, visible: true },
+ { id: 'integrations', label: t('project.settings.tabs.integrations'), icon: Settings2Icon, visible: true },
{ id: 'emails', label: t('project.settings.tabs.emails'), icon: MailIcon, visible: !isSelfhosted },
{ id: 'people', label: t('project.settings.tabs.people'), icon: UserRoundIcon, visible: true },
{
@@ -758,6 +794,120 @@ const ProjectSettings = () => {
{activeTab === 'emails' && !isSelfhosted ? <Emails projectId={id} /> : null}
{activeTab === 'people' ? <People project={project} reloadProject={reloadProject} /> : null}
+ {activeTab === 'integrations' ? (
+ <div>
+ <div className='rounded-lg border border-gray-200 p-4 dark:border-slate-800'>
+ <h3 className='mb-2 flex items-center gap-2 text-lg font-medium text-gray-900 dark:text-gray-50'>
+ <GoogleSearchConsoleSVG className='size-6' />
+ Google Search Console
+ </h3>
+ {gscConnected === null ? (
+ <Loader />
+ ) : !gscConnected ? (
+ <div className='flex flex-col items-center justify-between gap-4 md:flex-row'>
+ <p className='text-sm text-gray-800 dark:text-gray-200'>{t('project.settings.gsc.connect')}</p>
+ <Button
+ className='flex items-center gap-2'
+ type='button'
+ onClick={async () => {
+ try {
+ const { url } = await generateGSCAuthURL(id)
+ window.location.href = url
+ } catch (reason: any) {
+ toast.error(typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'))
+ }
+ }}
+ primary
+ regular
+ >
+ <GoogleGSVG className='size-4' />
+ {t('common.connect')}
+ </Button>
+ </div>
+ ) : (
+ <div className='flex flex-col gap-3'>
+ {_isEmpty(gscProperties) ? (
+ <p className='text-sm text-gray-800 dark:text-gray-200'>
+ {t('project.settings.gsc.accountConnected')}
+ </p>
+ ) : (
+ <div className='flex items-center gap-3'>
+ <div className='flex-1'>
+ <Select
+ items={_map(gscProperties, (p) => ({ key: p.siteUrl, label: p.siteUrl }))}
+ keyExtractor={(item) => item.key}
+ labelExtractor={(item) => item.label}
+ onSelect={(item: { key: string; label: string }) => setGscProperty(item.key)}
+ title={gscProperty || t('project.settings.gsc.selectProperty')}
+ selectedItem={gscProperty ? { key: gscProperty, label: gscProperty } : undefined}
+ />
+ </div>
+ <Button
+ type='button'
+ onClick={async () => {
+ if (!gscProperty) return
+ try {
+ await setGSCProperty(id, gscProperty)
+ toast.success(t('project.settings.gsc.connected'))
+ } catch (reason: any) {
+ toast.error(
+ typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'),
+ )
+ }
+ }}
+ primary
+ regular
+ >
+ {t('common.save')}
+ </Button>
+ </div>
+ )}
+ <div>
+ <Button
+ type='button'
+ onClick={async () => {
+ try {
+ await disconnectGSC(id)
+ setGscConnected(false)
+ setGscProperties([])
+ setGscProperty('')
+ toast.success(t('project.settings.gsc.disconnected'))
+ } catch (reason: any) {
+ toast.error(
+ typeof reason === 'string' ? reason : t('apiNotifications.somethingWentWrong'),
+ )
+ }
+ }}
+ regular
+ >
+ {t('common.disconnect')}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ <hr className='-mx-4 mt-4 mb-4 border-gray-200 dark:border-slate-800' />
+
+ <p className='text-sm text-gray-800 dark:text-gray-200'>
+ <Trans
+ t={t}
+ i18nKey='project.settings.gsc.connectDisclamer'
+ components={{
+ url: (
+ <a
+ href='https://search.google.com/search-console/about'
+ target='_blank'
+ rel='noopener noreferrer'
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
+ ),
+ }}
+ />
+ </p>
+ </div>
+ </div>
+ ) : null}
+
{activeTab === 'danger' ? (
<DangerZone
setShowTransfer={setShowTransfer}
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 5304bad14..b39a763ff 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -164,6 +164,7 @@ import Filters from './components/Filters'
import { FunnelChart } from './components/FunnelChart'
import FunnelsList from './components/FunnelsList'
const InteractiveMap = lazy(() => import('./components/InteractiveMap'))
+import Keywords from './components/Keywords'
import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'
import LockedDashboard from './components/LockedDashboard'
import { MetricCard, MetricCards, PerformanceMetricCards } from './components/MetricCards'
@@ -690,7 +691,7 @@ const ViewProjectContent = () => {
location: 'cc' | 'rg' | 'ct' | 'lc' | 'map'
page: 'pg' | 'host' | 'userFlow' | 'entryPage' | 'exitPage'
device: 'br' | 'os' | 'dv'
- source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co'
+ source: 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co' | 'keywords'
metadata: 'ce' | 'props'
}>({
location: 'cc',
@@ -3877,6 +3878,7 @@ const ViewProjectContent = () => {
if (type === 'traffic-sources') {
const trafficSourcesTabs = [
{ id: 'ref', label: t('project.mapping.ref') },
+ { id: 'keywords', label: t('project.mapping.keywords') },
[
{ id: 'so', label: t('project.mapping.so') },
{ id: 'me', label: t('project.mapping.me') },
@@ -3905,12 +3907,19 @@ const ViewProjectContent = () => {
onTabChange={(tab) =>
setPanelsActiveTabs({
...panelsActiveTabs,
- source: tab as 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co',
+ source: tab as 'ref' | 'so' | 'me' | 'ca' | 'te' | 'co' | 'keywords',
})
}
activeTabId={panelsActiveTabs.source}
- data={panelsData.data[panelsActiveTabs.source]}
+ data={
+ panelsActiveTabs.source === 'keywords'
+ ? []
+ : panelsData.data[panelsActiveTabs.source]
+ }
rowMapper={getTrafficSourcesRowMapper(panelsActiveTabs.source)}
+ customRenderer={
+ panelsActiveTabs.source === 'keywords' ? () => <Keywords /> : undefined
+ }
/>
)
}
diff --git a/web/app/pages/Project/View/components/Keywords.tsx b/web/app/pages/Project/View/components/Keywords.tsx
new file mode 100644
index 000000000..c34babea1
--- /dev/null
+++ b/web/app/pages/Project/View/components/Keywords.tsx
@@ -0,0 +1,113 @@
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link } from 'react-router'
+import { toast } from 'sonner'
+
+import { getGSCKeywords } from '~/api'
+import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import Loader from '~/ui/Loader'
+import routes from '~/utils/routes'
+
+import { useViewProjectContext } from '../ViewProject'
+import { getFormatDate } from '../ViewProject.helpers'
+
+const Keywords = () => {
+ const { id, project } = useCurrentProject()
+ const projectPassword = useProjectPassword(id)
+ const { t } = useTranslation('common')
+ const { dateRange, period, timezone } = useViewProjectContext()
+
+ const [isLoading, setIsLoading] = useState<boolean | null>(null)
+ const [keywords, setKeywords] = useState<{ name: string; count: number }[]>([])
+ const [notConnected, setNotConnected] = useState(false)
+
+ const [from, to] = useMemo(() => {
+ if (!dateRange) {
+ return [undefined, undefined]
+ }
+ return [getFormatDate(dateRange[0]), getFormatDate(dateRange[1])]
+ }, [dateRange])
+
+ const fetchKeywords = async () => {
+ if (isLoading) return
+ setIsLoading(true)
+ setNotConnected(false)
+ try {
+ const res = await getGSCKeywords(id, period, from, to, timezone, projectPassword)
+ setKeywords(res.keywords || [])
+ } catch (error: any) {
+ const message = typeof error === 'string' ? error : error?.message
+ if (message && (message as string).toLowerCase().includes('search console')) {
+ setNotConnected(true)
+ } else {
+ toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ }
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ useEffect(() => {
+ fetchKeywords()
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [period, from, to, timezone, id])
+
+ if (isLoading || isLoading === null) {
+ return <Loader />
+ }
+
+ if (notConnected) {
+ return (
+ <div className='mt-4 text-center'>
+ <p className='text-sm text-gray-800 dark:text-gray-200'>
+ {['owner', 'admin'].includes(project?.role || '')
+ ? t('project.connectGsc')
+ : t('project.gscConnectionRequired')}
+ </p>
+ {['owner', 'admin'].includes(project?.role || '') ? (
+ <Link
+ to={routes.project_settings.replace(':id', id)}
+ className='mt-2 inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-1 text-sm text-gray-800 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
+ >
+ {t('project.goToProjectSettings')}
+ </Link>
+ ) : null}
+ </div>
+ )
+ }
+
+ if (_isEmpty(keywords)) {
+ return (
+ <p className='mt-4 text-center text-sm text-gray-800 italic dark:text-gray-200'>{t('project.noKeywordsFound')}</p>
+ )
+ }
+
+ return (
+ <div className='max-h-[500px] overflow-y-auto'>
+ <table className='w-full border-separate border-spacing-y-1'>
+ <thead className='sticky top-0 z-10 bg-white dark:bg-slate-900'>
+ <tr className='text-base text-gray-900 dark:text-gray-50'>
+ <th className='w-2/3 pl-2 text-left'>{t('project.keyword')}</th>
+ <th className='w-1/3 pr-2 text-right'>{t('project.clicks')}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {_map(keywords, (k) => (
+ <tr key={`${k.name}-${k.count}`}>
+ <td className='rounded-l-md bg-gray-50 p-2 text-sm text-gray-900 dark:bg-slate-800 dark:text-gray-50'>
+ {k.name || t('common.notSet')}
+ </td>
+ <td className='rounded-r-md bg-gray-50 p-2 text-right text-sm text-gray-900 dark:bg-slate-800 dark:text-gray-50'>
+ {k.count}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )
+}
+
+export default Keywords
diff --git a/web/app/ui/icons/GoogleSearchConsole.tsx b/web/app/ui/icons/GoogleSearchConsole.tsx
new file mode 100644
index 000000000..ca4ef10a6
--- /dev/null
+++ b/web/app/ui/icons/GoogleSearchConsole.tsx
@@ -0,0 +1,32 @@
+const GoogleSearchConsoleSVG = ({ className }: { className?: string }) => (
+ <svg className={className} viewBox='6.239 2.66350997 503.09749003 503.10849003'>
+ <g fill='none'>
+ <path
+ d='m113.296 424.432-75.52 75.536c-5.825 5.804-15.247 5.804-21.072 0l-4.672-4.672c-5.793-5.823-5.793-15.233 0-21.056l75.52-75.536c5.827-5.814 15.26-5.814 21.088 0l4.656 4.656a14.88 14.88 0 0 1 0 21.072z'
+ fill='#fbbc04'
+ />
+ <path
+ d='m316 456h96.672a96.64 96.64 0 0 0 96.656-96.672v-260a96.64 96.64 0 0 0 -96.656-96.656 96.64 96.64 0 0 0 -96.672 96.656z'
+ fill='#4285f4'
+ />
+ <path
+ d='m156 456a96.64 96.64 0 0 0 96.672-96.672 96.64 96.64 0 0 0 -96.672-96.656 96.64 96.64 0 0 0 -96.672 96.656 96.64 96.64 0 0 0 96.672 96.672z'
+ fill='#fbbc04'
+ />
+ <path
+ d='m383.52 456h-94.192a96.64 96.64 0 0 1 -96.656-96.672v-126.656a96.64 96.64 0 0 1 96.656-96.672 96.64 96.64 0 0 1 96.672 96.672v220.864a2.464 2.464 0 0 1 -2.464 2.464z'
+ fill='#34a853'
+ />
+ <path
+ d='m386 453.536v-220.864c-.003-43.115-28.558-81.016-70-92.912v316.24h67.52a2.464 2.464 0 0 0 2.48-2.464z'
+ fill='#1967d2'
+ />
+ <path
+ d='m252.672 361.2c.006-39.228-23.701-74.567-60-89.44v89.44c0 27.52 11.52 52.368 30 69.968a96.384 96.384 0 0 0 30-69.968z'
+ fill='#ea4335'
+ />
+ </g>
+ </svg>
+)
+
+export default GoogleSearchConsoleSVG
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 4a69fa38b..8b4ba1daf 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -85,6 +85,8 @@
}
},
"common": {
+ "connect": "Connect",
+ "disconnect": "Disconnect",
"features": "Features",
"docs": "Docs",
"bookACall": "Book a call with the founder",
@@ -1042,10 +1044,17 @@
"co": "UTM Content",
"userFlow": "User flow",
"entryPage": "Entry page",
- "exitPage": "Exit page"
+ "exitPage": "Exit page",
+ "keywords": "Keywords"
},
+ "connectGsc": "Connect Google Search Console to see keywords for this project.",
+ "gscConnectionRequired": "Google Search Console connection is required to view keywords for this project. Ask the project administrator to connect it first.",
+ "goToProjectSettings": "Go to Project Settings",
+ "noKeywordsFound": "No keywords found for the selected period.",
"entryPages": "Entry pages",
"exitPages": "Exit pages",
+ "keyword": "Keyword",
+ "clicks": "Clicks",
"metamapping": {
"ev": {
"key": "Event key",
@@ -1119,13 +1128,22 @@
"organisation": "Organisation",
"shields": "Shields",
"access": "Access settings",
+ "gsc": {
+ "connect": "Connect your project to your Google Search Console account to get stats like what keywords people are using to find your website.",
+ "accountConnected": "Your account is connected. If you do not see your property list, ensure the account has access to your site in Search Console.",
+ "connected": "The project has been connected to your Google Search Console account.",
+ "disconnected": "The project has been disconnected from your Google Search Console account.",
+ "selectProperty": "Select a property",
+ "connectDisclamer": "For the integration to work, make sure you have set up your website on the <url>Google Search Console</url> first."
+ },
"tabs": {
"general": "General",
"access": "Access",
"shields": "Shields",
"emails": "Emails",
"people": "People",
- "danger": "Danger zone"
+ "danger": "Danger zone",
+ "integrations": "Integrations"
},
"botsProtectionLevel": {
"title": "Bots protection level",