π 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
feat: Funnel step sessions view
Blue Mouse034f1b3dcca2
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.tsindex 2b8b5c323..58c642201 100644--- a/backend/apps/cloud/src/analytics/analytics.controller.ts+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts@@ -48,6 +48,7 @@ import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { GetUserFlowDto } from './dto/getUserFlow.dto'import { GetFunnelsDto } from './dto/getFunnels.dto'+import { GetFunnelSessionsDto } from './dto/get-funnel-sessions.dto'import { AppLoggerService } from '../logger/logger.service'import {redis,@@ -480,6 +481,91 @@ export class AnalyticsController {return { funnel, totalPageviews }}+ @Get('funnel-sessions')+ @Auth(true, true)+ async getFunnelSessions(+ @Query() data: GetFunnelSessionsDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const {+ pid,+ period,+ from,+ to,+ timezone = DEFAULT_TIMEZONE,+ pages,+ funnelId,+ step,+ } = data++ const pagesArr = await this.analyticsService.getPagesArray(+ pages,+ funnelId,+ pid,+ )++ if (step > pagesArr.length) {+ throw new BadRequestException(+ `Step ${step} exceeds the number of funnel steps (${pagesArr.length})`,+ )+ }++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ const take = this.analyticsService.getSafeNumber(data.take, 30)+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)++ if (take > 150) {+ throw new BadRequestException(+ 'The maximum number of sessions to return is 150',+ )+ }++ this.logger.log(+ `pid: ${pid}, period: ${period}, step: ${step}, take: ${take}, skip: ${skip}`,+ 'GET /analytics/funnel-sessions',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'analytics',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const params = { pid, groupFrom: groupFromUTC, groupTo: groupToUTC }++ const sessions = await this.analyticsService.getFunnelSessionsList(+ pagesArr,+ params,+ safeTimezone,+ step,+ take,+ skip,+ )++ return { sessions, take, skip }+ }+@Get('meta')@Auth(true, true)async getCustomEventMetadata(diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.tsindex 39964e33d..c721e321a 100644--- a/backend/apps/cloud/src/analytics/analytics.service.ts+++ b/backend/apps/cloud/src/analytics/analytics.service.ts@@ -1633,6 +1633,168 @@ export class AnalyticsService {return { countries, sources }}+ async getFunnelSessionsList(+ pages: string[],+ params: any,+ safeTimezone: string,+ step: number,+ take = 30,+ skip = 0,+ ): Promise<object | void> {+ const pageParams: Record<string, string> = {}++ const pagesStr = _join(+ _map(pages, (value, index) => {+ pageParams[`v${index}`] = value+ return `value={v${index}:String}`+ }),+ ',',+ )++ const query = `+ WITH funnel_qualified AS (+ SELECT psid+ FROM (+ SELECT+ psid,+ windowFunnel(86400)(created, ${pagesStr}) AS level+ FROM (+ SELECT psid, pg AS value, created+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid != 0+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ UNION ALL+ SELECT psid, ev AS value, created+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid != 0+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ )+ GROUP BY psid+ )+ WHERE level >= {step:UInt32}+ ),+ distinct_sessions AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ any(cc) AS cc,+ any(os) AS os,+ any(br) AS br,+ min(toTimeZone(created, {timezone:String})) AS sessionStart,+ max(toTimeZone(created, {timezone:String})) AS lastActivity+ FROM (+ SELECT psid, pid, cc, os, br, created+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ UNION ALL+ SELECT psid, pid, cc, os, br, created+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ )+ GROUP BY psidCasted, pid+ ),+ pageview_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ event_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ error_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM errors+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ session_duration_agg AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,+ argMax(profileId, lastSeen) as profileId+ FROM sessions+ WHERE pid = {pid:FixedString(12)}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ first_session_per_profile AS (+ SELECT+ profileId,+ argMin(CAST(psid, 'String'), firstSeen) AS firstPsid+ FROM sessions FINAL+ WHERE pid = {pid:FixedString(12)}+ AND profileId IS NOT NULL+ AND profileId != ''+ GROUP BY profileId+ )+ SELECT+ dsf.psidCasted AS psid,+ dsf.cc,+ dsf.os,+ dsf.br,+ COALESCE(pc.count, 0) AS pageviews,+ COALESCE(ec.count, 0) AS customEvents,+ COALESCE(errc.count, 0) AS errors,+ dsf.sessionStart,+ dsf.lastActivity,+ if(dateDiff('second', dsf.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,+ sda.avg_duration AS sdur,+ sda.profileId AS profileId,+ if(startsWith(sda.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 1, 0) AS isIdentified,+ if(fsp.firstPsid = dsf.psidCasted, 1, 0) AS isFirstSession+ FROM distinct_sessions dsf+ LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid+ LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid+ LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid+ LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid+ LEFT JOIN first_session_per_profile fsp ON sda.profileId = fsp.profileId+ WHERE dsf.psidCasted IS NOT NULL+ ORDER BY dsf.sessionStart DESC+ LIMIT {take:UInt32}+ OFFSET {skip:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ ...params,+ ...pageParams,+ timezone: safeTimezone,+ step,+ take,+ skip,+ },+ })+ .then((resultSet) => resultSet.json())++ return data+ }+async getTotalPageviews(pid: string,groupFrom: string,diff --git a/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts b/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.tsnew file mode 100644index 000000000..954e537d4--- /dev/null+++ b/backend/apps/cloud/src/analytics/dto/get-funnel-sessions.dto.ts@@ -0,0 +1,73 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetFunnelSessionsDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description: 'A stringified array of pages/events for the funnel',+ required: false,+ })+ pages?: string++ @ApiProperty({+ description: 'Funnel ID (alternative to pages)',+ required: false,+ })+ funnelId?: string++ @ApiProperty({+ description: 'Funnel step to get sessions for (1-indexed)',+ })+ @Type(() => Number)+ @IsInt()+ @Min(1)+ step: number++ @Type(() => Number)+ @IsInt()+ @Min(0)+ @Max(150)+ take: number++ @Type(() => Number)+ @IsInt()+ @Min(0)+ skip: number+}diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.tsindex 337e76791..ef405f7f3 100644--- a/backend/apps/community/src/analytics/analytics.controller.ts+++ b/backend/apps/community/src/analytics/analytics.controller.ts@@ -47,6 +47,7 @@ import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'import { GetUserFlowDto } from './dto/getUserFlow.dto'import { GetFunnelsDto } from './dto/getFunnels.dto'+import { GetFunnelSessionsDto } from './dto/get-funnel-sessions.dto'import { AppLoggerService } from '../logger/logger.service'import { clickhouse } from '../common/integrations/clickhouse'import {@@ -468,6 +469,91 @@ export class AnalyticsController {return { funnel, totalPageviews }}+ @Get('funnel-sessions')+ @Auth(true, true)+ async getFunnelSessions(+ @Query() data: GetFunnelSessionsDto,+ @CurrentUserId() uid: string,+ @Headers() headers: { 'x-password'?: string },+ ) {+ const {+ pid,+ period,+ from,+ to,+ timezone = DEFAULT_TIMEZONE,+ pages,+ funnelId,+ step,+ } = data++ const pagesArr = await this.analyticsService.getPagesArray(+ pages,+ funnelId,+ pid,+ )++ if (step > pagesArr.length) {+ throw new BadRequestException(+ `Step ${step} exceeds the number of funnel steps (${pagesArr.length})`,+ )+ }++ await this.analyticsService.checkProjectAccess(+ pid,+ uid,+ headers['x-password'],+ )++ const take = this.analyticsService.getSafeNumber(data.take, 30)+ const skip = this.analyticsService.getSafeNumber(data.skip, 0)++ if (take > 150) {+ throw new BadRequestException(+ 'The maximum number of sessions to return is 150',+ )+ }++ this.logger.log(+ `pid: ${pid}, period: ${period}, step: ${step}, take: ${take}, skip: ${skip}`,+ 'GET /analytics/funnel-sessions',+ )++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.calculateTimeBucketForAllTime(+ pid,+ 'analytics',+ )++ diff = res.diff+ }++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(+ from,+ to,+ null,+ period,+ safeTimezone,+ diff,+ )++ const params = { pid, groupFrom: groupFromUTC, groupTo: groupToUTC }++ const sessions = await this.analyticsService.getFunnelSessionsList(+ pagesArr,+ params,+ safeTimezone,+ step,+ take,+ skip,+ )++ return { sessions, take, skip }+ }+@Get('meta')@Auth(true, true)async getCustomEventMetadata(diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.tsindex 894a72616..b5ac8a124 100644--- a/backend/apps/community/src/analytics/analytics.service.ts+++ b/backend/apps/community/src/analytics/analytics.service.ts@@ -1594,6 +1594,168 @@ export class AnalyticsService {return { countries, sources }}+ async getFunnelSessionsList(+ pages: string[],+ params: any,+ safeTimezone: string,+ step: number,+ take = 30,+ skip = 0,+ ): Promise<object | void> {+ const pageParams: Record<string, string> = {}++ const pagesStr = _join(+ _map(pages, (value, index) => {+ pageParams[`v${index}`] = value+ return `value={v${index}:String}`+ }),+ ',',+ )++ const query = `+ WITH funnel_qualified AS (+ SELECT psid+ FROM (+ SELECT+ psid,+ windowFunnel(86400)(created, ${pagesStr}) AS level+ FROM (+ SELECT psid, pg AS value, created+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid != 0+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ UNION ALL+ SELECT psid, ev AS value, created+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid != 0+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ )+ GROUP BY psid+ )+ WHERE level >= {step:UInt32}+ ),+ distinct_sessions AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ any(cc) AS cc,+ any(os) AS os,+ any(br) AS br,+ min(toTimeZone(created, {timezone:String})) AS sessionStart,+ max(toTimeZone(created, {timezone:String})) AS lastActivity+ FROM (+ SELECT psid, pid, cc, os, br, created+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ UNION ALL+ SELECT psid, pid, cc, os, br, created+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ )+ GROUP BY psidCasted, pid+ ),+ pageview_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM analytics+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ event_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM customEV+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ error_counts AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ count() as count+ FROM errors+ WHERE pid = {pid:FixedString(12)} AND psid IS NOT NULL+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ session_duration_agg AS (+ SELECT+ CAST(psid, 'String') AS psidCasted,+ pid,+ dateDiff('second', min(firstSeen), max(lastSeen)) as avg_duration,+ argMax(profileId, lastSeen) as profileId+ FROM sessions+ WHERE pid = {pid:FixedString(12)}+ AND psid IN (SELECT psid FROM funnel_qualified)+ GROUP BY psidCasted, pid+ ),+ first_session_per_profile AS (+ SELECT+ profileId,+ argMin(CAST(psid, 'String'), firstSeen) AS firstPsid+ FROM sessions FINAL+ WHERE pid = {pid:FixedString(12)}+ AND profileId IS NOT NULL+ AND profileId != ''+ GROUP BY profileId+ )+ SELECT+ dsf.psidCasted AS psid,+ dsf.cc,+ dsf.os,+ dsf.br,+ COALESCE(pc.count, 0) AS pageviews,+ COALESCE(ec.count, 0) AS customEvents,+ COALESCE(errc.count, 0) AS errors,+ dsf.sessionStart,+ dsf.lastActivity,+ if(dateDiff('second', dsf.lastActivity, now()) < ${LIVE_SESSION_THRESHOLD_SECONDS}, 1, 0) AS isLive,+ sda.avg_duration AS sdur,+ sda.profileId AS profileId,+ if(startsWith(sda.profileId, '${AnalyticsService.PROFILE_PREFIX_USER}'), 1, 0) AS isIdentified,+ if(fsp.firstPsid = dsf.psidCasted, 1, 0) AS isFirstSession+ FROM distinct_sessions dsf+ LEFT JOIN pageview_counts pc ON dsf.psidCasted = pc.psidCasted AND dsf.pid = pc.pid+ LEFT JOIN event_counts ec ON dsf.psidCasted = ec.psidCasted AND dsf.pid = ec.pid+ LEFT JOIN error_counts errc ON dsf.psidCasted = errc.psidCasted AND dsf.pid = errc.pid+ LEFT JOIN session_duration_agg sda ON dsf.psidCasted = sda.psidCasted AND dsf.pid = sda.pid+ LEFT JOIN first_session_per_profile fsp ON sda.profileId = fsp.profileId+ WHERE dsf.psidCasted IS NOT NULL+ ORDER BY dsf.sessionStart DESC+ LIMIT {take:UInt32}+ OFFSET {skip:UInt32}+ `++ const { data } = await clickhouse+ .query({+ query,+ query_params: {+ ...params,+ ...pageParams,+ timezone: safeTimezone,+ step,+ take,+ skip,+ },+ })+ .then((resultSet) => resultSet.json())++ return data+ }+async getTotalPageviews(pid: string,groupFrom: string,diff --git a/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts b/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.tsnew file mode 100644index 000000000..954e537d4--- /dev/null+++ b/backend/apps/community/src/analytics/dto/get-funnel-sessions.dto.ts@@ -0,0 +1,73 @@+import { ApiProperty } from '@nestjs/swagger'+import { Type } from 'class-transformer'+import {+ IsInt,+ IsNotEmpty,+ IsOptional,+ Matches,+ Max,+ Min,+} from 'class-validator'++import { PID_REGEX } from '../../common/constants'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'+import { ValidatePeriod } from '../decorators/validate-period.decorator'++export class GetFunnelSessionsDto {+ @ApiProperty({+ example: 'aUn1quEid-3',+ required: true,+ description: 'The project ID',+ })+ @IsNotEmpty()+ @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })+ pid: string++ @ApiProperty({ required: false })+ @IsOptional()+ @ValidatePeriod()+ period?: string++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string++ @ApiProperty({+ description: 'A stringified array of pages/events for the funnel',+ required: false,+ })+ pages?: string++ @ApiProperty({+ description: 'Funnel ID (alternative to pages)',+ required: false,+ })+ funnelId?: string++ @ApiProperty({+ description: 'Funnel step to get sessions for (1-indexed)',+ })+ @Type(() => Number)+ @IsInt()+ @Min(1)+ step: number++ @Type(() => Number)+ @IsInt()+ @Min(0)+ @Max(150)+ take: number++ @Type(() => Number)+ @IsInt()+ @Min(0)+ skip: number+}diff --git a/backend/blog-posts b/backend/blog-postsindex d90f881b5..44a9cf4a0 160000--- a/backend/blog-posts+++ b/backend/blog-posts@@ -1 +1 @@-Subproject commit d90f881b57f53f907fcff4e6d12fd401bbc68c7f+Subproject commit 44a9cf4a019ec2a2cc3af538eb06be548ab4f0addiff --git a/docs/.oxfmtrc.json b/docs/.oxfmtrc.jsonnew file mode 100644index 000000000..55c15df37--- /dev/null+++ b/docs/.oxfmtrc.json@@ -0,0 +1,4 @@+{+ "$schema": "./node_modules/oxfmt/configuration_schema.json",+ "ignorePatterns": []+}diff --git a/docs/content/docs/analytics-dashboard/funnels.mdx b/docs/content/docs/analytics-dashboard/funnels.mdxindex ddfc15500..e4643d821 100644--- a/docs/content/docs/analytics-dashboard/funnels.mdx+++ b/docs/content/docs/analytics-dashboard/funnels.mdx@@ -45,11 +45,17 @@ At the top of the funnel view, you will find a summary:The chart visualizes the flow of users through each step:-- **Visitors**: The green bar shows the number of users who successfully reached this step.-- **Dropoff**: The red bar indicates the number of users who left the funnel at this step (did not proceed to the next one).+- **Visitors**: The blue bar shows the number of users who successfully reached this step.+- **Dropoff**: The striped bar indicates the number of users who left the funnel at this step (did not proceed to the next one).This visualization helps you instantly spot the "leaky" parts of your flow where you are losing the most users.+### Exploring Sessions per Step++You can click on any bar in the funnel chart to open a sessions drawer showing the individual sessions that reached that step. These are not just sessions that visited the page β they are sessions that completed every prior funnel step in order, matching the same sequential logic the funnel itself uses.++For example, in a three-step funnel (`/pricing` β `/signup` β `/dashboard`), clicking the `/dashboard` bar will only show sessions where the visitor first viewed `/pricing`, then `/signup`, and then `/dashboard` β in that order.+## Managing FunnelsYou can manage your funnels directly from the main list:diff --git a/docs/content/docs/api/stats.mdx b/docs/content/docs/api/stats.mdxindex 99e3b8a97..75ddfda07 100644--- a/docs/content/docs/api/stats.mdx+++ b/docs/content/docs/api/stats.mdx@@ -1010,6 +1010,58 @@ A stringified JSON array of page paths to define the funnel steps.The ID of a saved funnel to retrieve.+<hr />++### GET /v1/log/funnel-sessions++Returns paginated sessions that reached a specific step in a funnel. Sessions are filtered using the same `windowFunnel` logic as the funnel analysis β only sessions that completed every prior step in order are included.++```bash+curl 'https://api.swetrix.com/v1/log/funnel-sessions?pid=YOUR_PROJECT_ID&funnelId=FUNNEL_ID&step=2&period=30d&take=30&skip=0'\+ -H "X-Api-Key: ${SWETRIX_API_KEY}"+```++```json title="Response"+{+ "sessions": [+ {+ "psid": "123456789",+ "cc": "US",+ "os": "Mac OS",+ "br": "Chrome",+ "pageviews": 5,+ "customEvents": 2,+ "errors": 0,+ "sessionStart": "2025-01-15 10:30:00",+ "lastActivity": "2025-01-15 10:35:00",+ "isLive": 0,+ "sdur": 300,+ "profileId": null,+ "isIdentified": 0,+ "isFirstSession": 1+ }+ ],+ "take": 30,+ "skip": 0+}+```++#### Parameters++The parameters are similar to the [`/log/funnel` endpoint](#get-v1logfunnel), with the addition of:++**step** (required)++The funnel step number to get sessions for (1-indexed). For example, `step=2` returns sessions that completed at least the first two funnel steps in order.++**take** (optional, default: `30`, max: `150`)++The number of sessions to return per page.++**skip** (optional, default: `0`)++The number of sessions to skip (for pagination).+### GET /v1/log/user-flowReturns the user flow diagram data, showing how users navigate through your website.diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 56452bad0..a7f974d83 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -987,6 +987,50 @@ export async function getSessionsServer()}+export interface FunnelSessionsResponse {+ sessions: Session[]+ take: number+ skip: number+}++export async function getFunnelSessionsServer(+ request: Request,+ pid: string,+ params: {+ period: string+ from?: string+ to?: string+ timezone?: string+ funnelId?: string+ step: number+ take?: number+ skip?: number+ password?: string+ },+): Promise<ServerFetchResult<FunnelSessionsResponse>> {+ const queryParams = new URLSearchParams()+ queryParams.append('pid', pid)+ queryParams.append('period', params.period)+ queryParams.append('step', String(params.step))+ queryParams.append('take', String(params.take || 30))+ queryParams.append('skip', String(params.skip || 0))+ if (params.funnelId) queryParams.append('funnelId', params.funnelId)+ if (params.from) queryParams.append('from', params.from)+ if (params.to) queryParams.append('to', params.to)+ if (params.timezone) queryParams.append('timezone', params.timezone)++ const headers: Record<string, string> = {}+ if (params.password) {+ headers['x-password'] = params.password+ }++ return serverFetch<FunnelSessionsResponse>(+ request,+ `log/funnel-sessions?${queryParams.toString()}`,+ { headers },+ )+}+interface PageflowItem {type: 'pageview' | 'event' | 'error'value: stringdiff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex fa81d03a9..6d237e5c7 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -1747,6 +1747,7 @@ const getSettingsFunnels = (totalPageviews: number,t: typeof i18next.t,language: string,+ onBarClick?: (stepIndex: number) => void,): ChartOptions => {const values = _map(funnel, (step) => {if (_startsWith(step.value, '/')) {@@ -1796,6 +1797,13 @@ const getSettingsFunnels = (onout: (_d: any, el: SVGElement) => {el?.style?.removeProperty('fill-opacity')},+ onclick: onBarClick+ ? (d: any) => {+ if (d?.index !== undefined) {+ onBarClick(d.index)+ }+ }+ : undefined,},bar: {radius: {diff --git a/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx b/web/app/pages/Project/tabs/Funnels/FunnelChart.tsxindex aecd0fa9c..f8a321f98 100644--- a/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx+++ b/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx@@ -13,6 +13,7 @@ interface FunnelChartProps {totalPageviews: numbert: anyclassName?: string+ onBarClick?: (stepIndex: number) => void}export const FunnelChart = ({@@ -20,12 +21,19 @@ export const FunnelChart = ({totalPageviews,t,className,+ onBarClick,}: FunnelChartProps) => {const { i18n } = useTranslation()const options: ChartOptions = useMemo(() => {- return getSettingsFunnels(funnel, totalPageviews, t, i18n.language)- }, [funnel, totalPageviews, t, i18n.language])+ return getSettingsFunnels(+ funnel,+ totalPageviews,+ t,+ i18n.language,+ onBarClick,+ )+ }, [funnel, totalPageviews, t, i18n.language, onBarClick])const dataNames = useMemo(() => ({@@ -36,8 +44,8 @@ export const FunnelChart = ({)const deps = useMemo(- () => [funnel, totalPageviews, t, i18n.language],- [funnel, totalPageviews, t, i18n.language],+ () => [funnel, totalPageviews, t, i18n.language, onBarClick],+ [funnel, totalPageviews, t, i18n.language, onBarClick],)return (diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsxindex 4876b273b..541fa1227 100644--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx@@ -4,7 +4,15 @@ import _find from 'lodash/find'import _includes from 'lodash/includes'import _isEmpty from 'lodash/isEmpty'import { FunnelIcon } from '@phosphor-icons/react'-import { useState, useEffect, useMemo, useRef, Suspense, use } from 'react'+import {+ useState,+ useEffect,+ useMemo,+ useCallback,+ useRef,+ Suspense,+ use,+} from 'react'import { useTranslation } from 'react-i18next'import {Link,@@ -40,6 +48,7 @@ import LoadingBar from '~/ui/LoadingBar'import { Text } from '~/ui/Text'import { nLocaleFormatter } from '~/utils/generic'import routes from '~/utils/routes'+import { SessionsDrawer } from '../Traffic/SessionsDrawer'import { LoaderView } from '../../View/components/LoaderView'interface DeferredFunnelData {@@ -76,7 +85,7 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {const revalidator = useRevalidator()const { isAuthenticated } = useAuth()const { funnelsRefreshTrigger } = useRefreshTriggers()- const { periodPairs } = useViewProjectContext()+ const { periodPairs, period, timezone, timeFormat } = useViewProjectContext()// Filter periods to only include those valid for funnelsconst timeBucketSelectorItems = useMemo(() => {@@ -98,6 +107,10 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {undefined,)const [dataLoading, setDataLoading] = useState(false)+ const [sessionsDrawer, setSessionsDrawer] = useState<{+ stepIndex: number+ label: string+ } | null>(null)// Initialize funnelAnalytics from loader dataconst [funnelAnalytics, setFunnelAnalytics] = useState<{@@ -260,6 +273,19 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {}}, [funnelAnalytics])+ const handleBarClick = useCallback(+ (stepIndex: number) => {+ if (!funnelAnalytics?.funnel?.[stepIndex]) return++ const step = funnelAnalytics.funnel[stepIndex]+ setSessionsDrawer({+ stepIndex,+ label: step.value,+ })+ },+ [funnelAnalytics],+ )+// When activeFunnel changes (URL params) and we have loader data, sync it// The actual data fetching happens via the loader when URL changesuseEffect(() => {@@ -356,6 +382,7 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {totalPageviews={funnelAnalytics.totalPageviews}t={t}className='mt-5 h-80 [&_svg]:!overflow-visible'+ onBarClick={handleBarClick}/>) : null}</div>@@ -378,6 +405,25 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {}}loading={funnelActionLoading}/>++ <SessionsDrawer+ isOpen={!!sessionsDrawer}+ onClose={() => setSessionsDrawer(null)}+ label={sessionsDrawer?.label || ''}+ projectId={id}+ timezone={timezone}+ timeFormat={timeFormat}+ period={period}+ from={searchParams.get('from') || undefined}+ to={searchParams.get('to') || undefined}+ funnelId={activeFunnel?.id}+ funnelStep={sessionsDrawer ? sessionsDrawer.stepIndex + 1 : undefined}+ totalCount={+ sessionsDrawer+ ? funnelAnalytics?.funnel?.[sessionsDrawer.stepIndex]?.events+ : undefined+ }+ /></>)}diff --git a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsxindex 08bd70fd7..98c345dc6 100644--- a/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx+++ b/web/app/pages/Project/tabs/Traffic/SessionsDrawer.tsx@@ -3,7 +3,7 @@ import _map from 'lodash/map'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import type { SessionsResponse } from '~/api/api.server'+import type { SessionsResponse, FunnelSessionsResponse } from '~/api/api.server'import type { Session as SessionType } from '~/lib/models/Project'import {Drawer,@@ -20,16 +20,19 @@ import { Session } from '../Sessions/Sessions'const SESSIONS_TAKE = 30+type SessionsPageResult = SessionsResponse | FunnelSessionsResponse+async function fetchSessionsPage(+ action: string,projectId: string,params: Record<string, unknown>,signal?: AbortSignal,-): Promise<SessionsResponse | null> {+): Promise<SessionsPageResult | null> {const response = await fetch('/api/analytics', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({- action: 'getSessions',+ action,projectId,params,}),@@ -41,7 +44,7 @@ async function fetchSessionsPage(}const result = (await response.json()) as {- data: SessionsResponse | null+ data: SessionsPageResult | nullerror: string | null}@@ -55,13 +58,17 @@ async function fetchSessionsPage(interface SessionsDrawerProps {isOpen: booleanonClose: () => void- from: string- to: string+ from?: string+ to?: stringlabel: stringprojectId: stringtimezone: stringtimeFormat: '12-hour' | '24-hour'filters?: any[]+ period?: string+ funnelId?: string+ funnelStep?: number+ totalCount?: number}export const SessionsDrawer = ({@@ -74,9 +81,14 @@ export const SessionsDrawer = ({timezone,timeFormat,filters,+ period = 'custom',+ funnelId,+ funnelStep,+ totalCount,}: SessionsDrawerProps) => {const { t } = useTranslation('common')const stableFilters = useMemo(() => filters ?? [], [filters])+ const isFunnelMode = !!(funnelId && funnelStep)const [sessions, setSessions] = useState<SessionType[]>([])const [skip, setSkip] = useState(0)const [hasMore, setHasMore] = useState(true)@@ -94,22 +106,41 @@ export const SessionsDrawer = ({append: boolean,signal?: AbortSignal,): Promise<boolean> => {- let result: SessionsResponse | null = null+ let result: SessionsPageResult | null = nulltry {- result = await fetchSessionsPage(- projectId,- {- period: 'custom',- from,- to,- timezone,- filters: stableFilters,- take: SESSIONS_TAKE,- skip: currentSkip,- },- signal,- )+ if (isFunnelMode) {+ result = await fetchSessionsPage(+ 'getFunnelSessions',+ projectId,+ {+ period,+ from,+ to,+ timezone,+ funnelId,+ step: funnelStep,+ take: SESSIONS_TAKE,+ skip: currentSkip,+ },+ signal,+ )+ } else {+ result = await fetchSessionsPage(+ 'getSessions',+ projectId,+ {+ period,+ from,+ to,+ timezone,+ filters: stableFilters,+ take: SESSIONS_TAKE,+ skip: currentSkip,+ },+ signal,+ )+ }} catch (e) {if (signal?.aborted) return falsesetError(@@ -136,7 +167,18 @@ export const SessionsDrawer = ({return true},- [projectId, from, to, timezone, stableFilters, t],+ [+ projectId,+ period,+ from,+ to,+ timezone,+ isFunnelMode,+ funnelId,+ funnelStep,+ stableFilters,+ t,+ ],)useEffect(() => {@@ -165,7 +207,7 @@ export const SessionsDrawer = ({clearTimeout(timer)controller.abort()}- }, [isOpen, from, to, loadSessions])+ }, [isOpen, period, from, to, loadSessions])const loadMore = useCallback(async () => {if (loadingRef.current || !hasMore) return@@ -226,11 +268,18 @@ export const SessionsDrawer = ({<DrawerDescription>{label}</DrawerDescription></div><div className='ml-3 flex shrink-0 items-center gap-2'>- {!initialLoading && sessions.length > 0 ? (+ {!initialLoading &&+ (totalCount != null || sessions.length > 0) ? (<span className='inline-flex items-center gap-1 rounded-md bg-gray-100 px-2 py-1 text-xs font-medium text-gray-600 dark:bg-slate-800 dark:text-gray-300'><UsersIcon className='size-3.5' />- {sessions.length}- {hasMore ? '+' : ''}+ {totalCount != null ? (+ totalCount+ ) : (+ <>+ {sessions.length}+ {hasMore ? '+' : ''}+ </>+ )}</span>) : null}<DrawerClose asChild>diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.tsindex e48cd69d4..586cbb133 100644--- a/web/app/routes/api.analytics.ts+++ b/web/app/routes/api.analytics.ts@@ -6,6 +6,7 @@ import {import {getSessionsServer,+ getFunnelSessionsServer,getErrorsServer,getFeatureFlagStatsServer,getFeatureFlagProfilesServer,@@ -40,6 +41,7 @@ import {type AnalyticsParams,type AnalyticsFilter,type SessionsResponse,+ type FunnelSessionsResponse,type ErrorsResponse,type FeatureFlagStats,type FeatureFlagProfilesResponse,@@ -121,6 +123,7 @@ interface ProxyRequest {| 'getRevenueStatus'| 'getRevenueData'| 'getOverallStats'+ | 'getFunnelSessions'projectId: stringpids?: string[]flagId?: string@@ -149,6 +152,8 @@ interface ProxyRequest {profileType?: 'all' | 'anonymous' | 'identified'page?: stringquery?: string+ funnelId?: string+ step?: number}}@@ -198,6 +203,28 @@ export async function action({ request }: ActionFunctionArgs) {})}+ case 'getFunnelSessions': {+ const result = await getFunnelSessionsServer(request, projectId, {+ period: analyticsParams.period,+ from: analyticsParams.from,+ to: analyticsParams.to,+ timezone: analyticsParams.timezone,+ funnelId: params.funnelId,+ step: params.step ?? 1,+ take: params.take,+ skip: params.skip,+ password: analyticsParams.password,+ })+ return data<ProxyResponse<FunnelSessionsResponse>>({+ data: result.data,+ error: result.error+ ? Array.isArray(result.error)+ ? result.error.join(', ')+ : result.error+ : null,+ })+ }+case 'getErrors': {const errorsParams = { ...analyticsParams, options: params.options }const result = await getErrorsServer(request, projectId, errorsParams)