Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add filtering by site

Bill Yang08435e4c3cdd
diff --git a/client/src/app/[site]/components/Header/DateSelector.tsx b/client/src/app/[site]/components/Header/DateSelector.tsx
index dca61716c..a0b6fbaea 100644
--- a/client/src/app/[site]/components/Header/DateSelector.tsx
+++ b/client/src/app/[site]/components/Header/DateSelector.tsx
@@ -7,7 +7,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import { Time, useTimeSelection } from "@/lib/timeSelectionStore";
+import { Time, useStore } from "@/lib/store";
import { DateTime } from "luxon";
import { CustomDateRangePicker } from "./CustomDateRangePicker";
@@ -28,7 +28,7 @@ const getLabel = (time: Time) => {
};
export function DateSelector() {
- const { time, setTime } = useTimeSelection();
+ const { time, setTime } = useStore();
return (
<DropdownMenu>
diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsx
index 190531bfe..150253658 100644
--- a/client/src/app/[site]/components/Header/Header.tsx
+++ b/client/src/app/[site]/components/Header/Header.tsx
@@ -3,16 +3,12 @@ import { Circle } from "@phosphor-icons/react";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
-import {
- goBack,
- goForward,
- Time,
- useTimeSelection,
-} from "@/lib/timeSelectionStore";
+import { goBack, goForward, Time, useStore } from "@/lib/store";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DateSelector } from "./DateSelector";
import { DateTime } from "luxon";
import { authedFetch } from "@/hooks/utils";
+import { useGetLiveUsercount } from "../../../../hooks/api";
const canGoForward = (time: Time) => {
const currentDay = DateTime.now().startOf("day");
@@ -40,15 +36,8 @@ const canGoForward = (time: Time) => {
};
export function Header() {
- const { data } = useQuery<{ count: number }>({
- queryKey: ["active-sessions"],
- queryFn: () =>
- authedFetch(
- `${process.env.NEXT_PUBLIC_BACKEND_URL}/live-user-count`
- ).then((res) => res.json()),
- });
-
- const { time } = useTimeSelection();
+ const { data } = useGetLiveUsercount();
+ const { time } = useStore();
return (
<div className="flex items-center justify-between py-2">
diff --git a/client/src/app/[site]/components/MainSection/BucketSelection.tsx b/client/src/app/[site]/components/MainSection/BucketSelection.tsx
index 5a342bc73..eab8a3f06 100644
--- a/client/src/app/[site]/components/MainSection/BucketSelection.tsx
+++ b/client/src/app/[site]/components/MainSection/BucketSelection.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Time, useTimeSelection } from "@/lib/timeSelectionStore";
+import { Time, useStore } from "@/lib/store";
import {
SelectItem,
Select,
@@ -78,7 +78,7 @@ const getOptions = (time: Time) => {
};
export function BucketSelection() {
- const { bucket, setBucket, time } = useTimeSelection();
+ const { bucket, setBucket, time } = useStore();
return (
<Select value={bucket} onValueChange={setBucket}>
diff --git a/client/src/app/[site]/components/MainSection/Chart.tsx b/client/src/app/[site]/components/MainSection/Chart.tsx
index 85fb7e0a9..f3e75dabb 100644
--- a/client/src/app/[site]/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/components/MainSection/Chart.tsx
@@ -4,7 +4,7 @@ import { round } from "lodash";
import { DateTime } from "luxon";
import { APIResponse, GetPageViewsResponse } from "@/hooks/api";
import { nivoTheme } from "@/lib/nivo";
-import { Time, useTimeSelection } from "@/lib/timeSelectionStore";
+import { Time, useStore } from "@/lib/store";
export const formatter = Intl.NumberFormat("en", { notation: "compact" });
@@ -58,7 +58,7 @@ export function Chart({
previousData: APIResponse<GetPageViewsResponse> | undefined;
max: number;
}) {
- const { time, bucket } = useTimeSelection();
+ const { time, bucket } = useStore();
// When the current period has more datapoints than the previous period,
// we need to shift the previous datapoints to the right by the difference in length
diff --git a/client/src/app/[site]/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/components/MainSection/PreviousChart.tsx
index c1eeb2308..9ccea40c6 100644
--- a/client/src/app/[site]/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/components/MainSection/PreviousChart.tsx
@@ -3,7 +3,7 @@ import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
import { APIResponse, GetPageViewsResponse } from "@/hooks/api";
import { nivoTheme } from "@/lib/nivo";
-import { Time, useTimeSelection } from "@/lib/timeSelectionStore";
+import { Time, useStore } from "@/lib/store";
import { useMemo } from "react";
const getMin = (time: Time) => {
@@ -34,7 +34,7 @@ export function PreviousChart({
data: APIResponse<GetPageViewsResponse> | undefined;
max: number;
}) {
- const { previousTime: time } = useTimeSelection();
+ const { previousTime: time } = useStore();
const formattedData = data?.data?.map((e) => ({
x: DateTime.fromSQL(e.time).toUTC().toFormat("yyyy-MM-dd HH:mm:ss"),
diff --git a/client/src/app/[site]/page.tsx b/client/src/app/[site]/page.tsx
index 1582c08c0..b9afbedff 100644
--- a/client/src/app/[site]/page.tsx
+++ b/client/src/app/[site]/page.tsx
@@ -1,3 +1,5 @@
+"use client";
+import { usePathname } from "next/navigation";
import { Header } from "./components/Header/Header";
import { MainSection } from "./components/MainSection/MainSection";
import { Browsers } from "./components/sections/Browsers/Browsers";
@@ -7,8 +9,23 @@ import { Map } from "./components/sections/Map/Map";
import { OperatingSystems } from "./components/sections/OperatingSystems/OperatingSystems";
import { Pages } from "./components/sections/Pages/Pages";
import { Referrers } from "./components/sections/Referrers/Referrers";
+import { useStore } from "../../lib/store";
+import { useEffect } from "react";
export default function SitePage() {
+ const pathname = usePathname();
+ const { setSite, site } = useStore();
+
+ useEffect(() => {
+ if (pathname.includes("/")) {
+ setSite(pathname.split("/")[1]);
+ }
+ }, [pathname]);
+
+ if (!site) {
+ return null;
+ }
+
return (
<>
<Header />
diff --git a/client/src/app/layout.tsx b/client/src/app/layout.tsx
index d08db8407..4e6f99bba 100644
--- a/client/src/app/layout.tsx
+++ b/client/src/app/layout.tsx
@@ -7,7 +7,7 @@ import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { redirect, usePathname } from "next/navigation";
import { useEffect } from "react";
-import { userStore } from "../lib/useStore";
+import { userStore } from "../lib/userStore";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
diff --git a/client/src/app/login/page.tsx b/client/src/app/login/page.tsx
index 94dea674d..f0218bd9e 100644
--- a/client/src/app/login/page.tsx
+++ b/client/src/app/login/page.tsx
@@ -14,7 +14,7 @@ import { Label } from "@/components/ui/label";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { authClient } from "../../lib/auth";
-import { userStore } from "../../lib/useStore";
+import { userStore } from "../../lib/userStore";
export default function Page() {
const [username, setUsername] = useState("");
diff --git a/client/src/app/page.tsx b/client/src/app/page.tsx
index 9dce405b6..44a05e32c 100644
--- a/client/src/app/page.tsx
+++ b/client/src/app/page.tsx
@@ -14,7 +14,7 @@ export default function Home() {
</div>
<div className="grid grid-cols-3 gap-4 mt-4">
{sites?.data?.map((site) => (
- <Link href={`/${site.domain}`} key={site.site_id}>
+ <Link href={`/${site.site_id}`} key={site.site_id}>
<div className="flex p-4 rounded-lg bg-neutral-900 text-lg font-semibold gap-2">
<img
className="w-6 mr-1"
diff --git a/client/src/hooks/api.ts b/client/src/hooks/api.ts
index 624c23ff4..6852705ec 100644
--- a/client/src/hooks/api.ts
+++ b/client/src/hooks/api.ts
@@ -3,7 +3,7 @@ import {
useQuery,
UseQueryResult,
} from "@tanstack/react-query";
-import { useTimeSelection } from "../lib/timeSelectionStore";
+import { useStore } from "../lib/store";
import { authedFetch, getStartAndEndDate } from "./utils";
export type APIResponse<T> = {
@@ -11,22 +11,33 @@ export type APIResponse<T> = {
error?: string;
};
+export function useGetLiveUsercount() {
+ const { site } = useStore();
+ return useQuery({
+ queryKey: ["live-user-count", site],
+ queryFn: () =>
+ authedFetch(
+ `${process.env.NEXT_PUBLIC_BACKEND_URL}/live-user-count/${site}`
+ ).then((res) => res.json()),
+ });
+}
+
type PeriodTime = "current" | "previous";
export function useGenericQuery<T>(
endpoint: string,
periodTime?: PeriodTime
): UseQueryResult<APIResponse<T>> {
- const { time, previousTime } = useTimeSelection();
+ const { time, previousTime, site } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
const { startDate, endDate } = getStartAndEndDate(timeToUse);
return useQuery({
- queryKey: [endpoint, timeToUse],
+ queryKey: [endpoint, timeToUse, site],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(
- `${process.env.NEXT_PUBLIC_BACKEND_URL}/${endpoint}?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}`
+ `${process.env.NEXT_PUBLIC_BACKEND_URL}/${endpoint}?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}&site=${site}`
).then((res) => res.json());
},
staleTime: Infinity,
@@ -102,17 +113,17 @@ export type GetPageViewsResponse = {
export function useGetPageviews(
periodTime?: PeriodTime
): UseQueryResult<APIResponse<GetPageViewsResponse>> {
- const { time, previousTime, bucket } = useTimeSelection();
+ const { time, previousTime, bucket, site } = useStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
const { startDate, endDate } = getStartAndEndDate(timeToUse);
return useQuery({
- queryKey: ["pageviews", timeToUse, bucket],
+ queryKey: ["pageviews", timeToUse, bucket, site],
queryFn: () => {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
return authedFetch(
- `${process.env.NEXT_PUBLIC_BACKEND_URL}/pageviews?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}&bucket=${bucket}`
+ `${process.env.NEXT_PUBLIC_BACKEND_URL}/pageviews?startDate=${startDate}&endDate=${endDate}&timezone=${timezone}&bucket=${bucket}&site=${site}`
).then((res) => res.json());
},
placeholderData: keepPreviousData,
diff --git a/client/src/hooks/utils.ts b/client/src/hooks/utils.ts
index e9e32fdf2..0ba8d13d2 100644
--- a/client/src/hooks/utils.ts
+++ b/client/src/hooks/utils.ts
@@ -1,4 +1,4 @@
-import { Time } from "@/lib/timeSelectionStore";
+import { Time } from "@/lib/store";
export function getStartAndEndDate(time: Time) {
if (time.mode === "range") {
diff --git a/client/src/lib/timeSelectionStore.ts b/client/src/lib/store.ts
similarity index 94%
rename from client/src/lib/timeSelectionStore.ts
rename to client/src/lib/store.ts
index e8ec91e99..6c7545511 100644
--- a/client/src/lib/timeSelectionStore.ts
+++ b/client/src/lib/store.ts
@@ -32,6 +32,8 @@ export type Time = DateMode | DateRangeMode | WeekMode | MonthMode | YearMode;
export type TimeBucket = "hour" | "day" | "week" | "month";
type Store = {
+ site: string;
+ setSite: (site: string) => void;
time: Time;
previousTime: Time;
setTime: (time: Time) => void;
@@ -39,7 +41,9 @@ type Store = {
setBucket: (bucket: TimeBucket) => void;
};
-export const useTimeSelection = create<Store>((set) => ({
+export const useStore = create<Store>((set) => ({
+ site: "",
+ setSite: (site) => set({ site }),
time: {
mode: "day",
day: DateTime.now().toISODate(),
@@ -105,7 +109,7 @@ export const useTimeSelection = create<Store>((set) => ({
}));
export const goBack = () => {
- const { time, setTime } = useTimeSelection.getState();
+ const { time, setTime } = useStore.getState();
if (time.mode === "day") {
setTime({
@@ -128,7 +132,7 @@ export const goBack = () => {
};
export const goForward = () => {
- const { time, setTime } = useTimeSelection.getState();
+ const { time, setTime } = useStore.getState();
if (time.mode === "day") {
setTime({
diff --git a/client/src/lib/useStore.ts b/client/src/lib/userStore.ts
similarity index 100%
rename from client/src/lib/useStore.ts
rename to client/src/lib/userStore.ts
diff --git a/server/src/api/getBrowsers.ts b/server/src/api/getBrowsers.ts
index 8dda91e03..8f3a32957 100644
--- a/server/src/api/getBrowsers.ts
+++ b/server/src/api/getBrowsers.ts
@@ -10,7 +10,9 @@ type GetBrowsersResponse = {
}[];
export async function getBrowsers(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getBrowsers(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY browser ORDER BY count desc;
`;
diff --git a/server/src/api/getCountries.ts b/server/src/api/getCountries.ts
index c5fd07311..37b9283f2 100644
--- a/server/src/api/getCountries.ts
+++ b/server/src/api/getCountries.ts
@@ -10,7 +10,9 @@ type GetCountriesResponse = {
}[];
export async function getCountries(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getCountries(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY country ORDER BY count desc;
`;
diff --git a/server/src/api/getDevices.ts b/server/src/api/getDevices.ts
index dad05d7f0..922a7d06b 100644
--- a/server/src/api/getDevices.ts
+++ b/server/src/api/getDevices.ts
@@ -10,7 +10,9 @@ type GetDevicesResponse = {
}[];
export async function getDevices(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getDevices(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY device_type ORDER BY count desc;
`;
diff --git a/server/src/api/getLiveUsercount.ts b/server/src/api/getLiveUsercount.ts
index 1d5cd83eb..d071b6fb6 100644
--- a/server/src/api/getLiveUsercount.ts
+++ b/server/src/api/getLiveUsercount.ts
@@ -1,6 +1,12 @@
+import { FastifyReply, FastifyRequest } from "fastify";
import { sql } from "../db/postgres/postgres.js";
-export const getLiveUsercount = async () => {
- const result = await sql`SELECT COUNT(*) FROM active_sessions`;
- return result[0].count;
+export const getLiveUsercount = async (
+ { params: { site } }: FastifyRequest<{ Params: { site: string } }>,
+ res: FastifyReply
+) => {
+ const result =
+ await sql`SELECT COUNT(*) FROM active_sessions WHERE site_id = ${site}`;
+
+ return res.send({ count: result[0].count });
};
diff --git a/server/src/api/getOperatingSystems.ts b/server/src/api/getOperatingSystems.ts
index ba757eb2a..e773c66db 100644
--- a/server/src/api/getOperatingSystems.ts
+++ b/server/src/api/getOperatingSystems.ts
@@ -10,7 +10,9 @@ type GetOperatingSystemsResponse = {
}[];
export async function getOperatingSystems(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getOperatingSystems(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY operating_system ORDER BY count desc;
`;
diff --git a/server/src/api/getOverview.ts b/server/src/api/getOverview.ts
index a94c6bead..a381e4751 100644
--- a/server/src/api/getOverview.ts
+++ b/server/src/api/getOverview.ts
@@ -13,7 +13,9 @@ type GetOverviewResponse = {
};
export async function getOverview(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -43,6 +45,7 @@ export async function getOverview(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY session_id
)
) AS session_stats
@@ -55,6 +58,7 @@ export async function getOverview(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
) AS page_stats
`;
diff --git a/server/src/api/getPageViews.ts b/server/src/api/getPageViews.ts
index 59f85ece1..8b25a048d 100644
--- a/server/src/api/getPageViews.ts
+++ b/server/src/api/getPageViews.ts
@@ -15,13 +15,14 @@ type GetPageViewsResponse = { time: string; pageviews: number }[];
export async function getPageViews(
{
- query: { startDate, endDate, timezone, bucket },
+ query: { startDate, endDate, timezone, bucket, site },
}: FastifyRequest<{
Querystring: {
startDate: string;
endDate: string;
timezone: string;
bucket: TimeBucket;
+ site: string;
};
}>,
res: FastifyReply
@@ -33,6 +34,7 @@ export async function getPageViews(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY
time
ORDER BY
diff --git a/server/src/api/getPages.ts b/server/src/api/getPages.ts
index 68998e684..42914a185 100644
--- a/server/src/api/getPages.ts
+++ b/server/src/api/getPages.ts
@@ -10,7 +10,9 @@ type GetPagesResponse = {
}[];
export async function getPages(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getPages(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY pathname
ORDER BY count desc
LIMIT 100;
diff --git a/server/src/api/getReferrers.ts b/server/src/api/getReferrers.ts
index 8b606dc3f..f60015057 100644
--- a/server/src/api/getReferrers.ts
+++ b/server/src/api/getReferrers.ts
@@ -10,7 +10,9 @@ type GetReferrersResponse = {
}[];
export async function getReferrers(
- { query: { startDate, endDate, timezone } }: FastifyRequest<GenericRequest>,
+ {
+ query: { startDate, endDate, timezone, site },
+ }: FastifyRequest<GenericRequest>,
res: FastifyReply
) {
const query = `
@@ -21,6 +23,7 @@ export async function getReferrers(
FROM pageviews
WHERE
${getTimeStatement(startDate, endDate, timezone)}
+ AND site_id = ${site}
GROUP BY referrer
ORDER BY count desc
LIMIT 100;
diff --git a/server/src/api/types.ts b/server/src/api/types.ts
index 30bea3de7..32ab153fc 100644
--- a/server/src/api/types.ts
+++ b/server/src/api/types.ts
@@ -1,3 +1,8 @@
export interface GenericRequest {
- Querystring: { startDate: string; endDate: string; timezone: string };
+ Querystring: {
+ startDate: string;
+ endDate: string;
+ timezone: string;
+ site: string;
+ };
}
diff --git a/server/src/index.ts b/server/src/index.ts
index b8891f44d..100665a4f 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -4,7 +4,7 @@ import { toNodeHandler } from "better-auth/node";
import Fastify from "fastify";
import cron from "node-cron";
import { dirname, join } from "path";
-import { Headers, HeadersInit } from "undici"; // Ensure Undici is used for Headers
+import { Headers, HeadersInit } from "undici";
import { fileURLToPath } from "url";
import { addSite } from "./actions/sites/addSite.js";
import { deleteSite } from "./actions/sites/deleteSite.js";
@@ -25,7 +25,6 @@ import { cleanupOldSessions } from "./db/postgres/session-cleanup.js";
import { auth } from "./lib/auth.js";
import { mapHeaders } from "./lib/betterAuth.js";
-// ESM replacement for __dirname:
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -114,10 +113,7 @@ server.addHook("onRequest", async (request, reply) => {
}
});
-server.get("/live-user-count", async () => {
- return { count: await getLiveUsercount() };
-});
-
+server.get("/live-user-count/:site", getLiveUsercount);
server.get("/overview", getOverview);
server.get("/countries", getCountries);
server.get("/browsers", getBrowsers);