Skip to content

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

feat: delete session replays (#681)

Stijn3e3c0220054f
diff --git a/client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts b/client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts
new file mode 100644
index 000000000..c48b64a23
--- /dev/null
+++ b/client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts
@@ -0,0 +1,29 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useStore } from "../../../lib/store";
+import { authedFetch } from "../../utils";
+
+interface DeleteSessionReplayParams {
+ sessionId: string;
+}
+
+export function useDeleteSessionReplay() {
+ const { site } = useStore();
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async ({ sessionId }: DeleteSessionReplayParams) => {
+ const response = await authedFetch<{ success: boolean }>(
+ `/session-replay/${sessionId}/${site}`,
+ {},
+ {
+ method: "DELETE",
+ }
+ );
+ return response;
+ },
+ onSuccess: () => {
+ // Invalidate the session replay list query to refetch data
+ queryClient.invalidateQueries({ queryKey: ["session-replays", site] });
+ },
+ });
+}
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index f3fb00f51..ab5de8d63 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -1,6 +1,7 @@
-import { Clock, MousePointerClick } from "lucide-react";
+import { Clock, MousePointerClick, Trash2 } from "lucide-react";
import { DateTime } from "luxon";
import Link from "next/link";
+import { useState } from "react";
import {
BrowserTooltipIcon,
CountryFlagTooltipIcon,
@@ -9,8 +10,21 @@ import {
} from "../../../../components/TooltipIcons/TooltipIcons";
import { Badge } from "../../../../components/ui/badge";
import { Skeleton } from "../../../../components/ui/skeleton";
+import { Button } from "../../../../components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "../../../../components/ui/alert-dialog";
import { cn, formatter } from "../../../../lib/utils";
import { useReplayStore } from "./replayStore";
+import { useDeleteSessionReplay } from "../../../../api/analytics/sessionReplay/useDeleteSessionReplay";
interface SessionReplayListItem {
session_id: string;
@@ -33,7 +47,9 @@ interface SessionReplayListItem {
}
export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
- const { sessionId, setSessionId } = useReplayStore();
+ const { sessionId, setSessionId, resetPlayerState } = useReplayStore();
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const deleteSessionReplay = useDeleteSessionReplay();
const startTime = DateTime.fromSQL(replay.start_time, {
zone: "utc",
}).toLocal();
@@ -45,10 +61,25 @@ export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
};
+ const handleDelete = async () => {
+ try {
+ await deleteSessionReplay.mutateAsync({ sessionId: replay.session_id });
+
+ // If the deleted replay was selected, reset the player
+ if (sessionId === replay.session_id) {
+ resetPlayerState();
+ }
+
+ setIsDialogOpen(false);
+ } catch (error) {
+ console.error("Failed to delete session replay:", error);
+ }
+ };
+
return (
<div
className={cn(
- "bg-neutral-900 border-b border-neutral-800 p-3 hover:bg-neutral-800/80 transition-colors cursor-pointer w-[200px]",
+ "bg-neutral-900 border-b border-neutral-800 p-3 hover:bg-neutral-800/80 transition-colors cursor-pointer w-[200px] group relative",
// "bg-neutral-900 border border-neutral-800 rounded-lg p-3 hover:bg-neutral-800/50 transition-colors cursor-pointer",
sessionId === replay.session_id && "bg-neutral-800/80"
)}
@@ -67,6 +98,44 @@ export function ReplayCard({ replay }: { replay: SessionReplayListItem }) {
{formatDuration(duration)}
</div>
)}
+
+ <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
+ <AlertDialogTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="ml-auto opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6 p-0 hover:bg-red-500/20 hover:text-red-400"
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsDialogOpen(true);
+ }}
+ >
+ <Trash2 className="w-3 h-3" />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent onClick={(e) => e.stopPropagation()}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Session Replay</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete this session replay? This action cannot be undone and will permanently
+ remove the replay data.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={(e) => e.stopPropagation()}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={(e) => {
+ e.stopPropagation();
+ handleDelete();
+ }}
+ disabled={deleteSessionReplay.isPending}
+ >
+ {deleteSessionReplay.isPending ? "Deleting..." : "Delete"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
<div className="text-xs text-neutral-200 truncate mb-2">
diff --git a/server/src/api/sessionReplay/deleteSessionReplay.ts b/server/src/api/sessionReplay/deleteSessionReplay.ts
new file mode 100644
index 000000000..53bb88ea7
--- /dev/null
+++ b/server/src/api/sessionReplay/deleteSessionReplay.ts
@@ -0,0 +1,45 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
+import { SessionReplayQueryService } from "../../services/replay/sessionReplayQueryService.js";
+
+export async function deleteSessionReplay(
+ request: FastifyRequest<{
+ Params: {
+ sessionId: string;
+ site: string;
+ };
+ }>,
+ reply: FastifyReply
+) {
+ const { sessionId, site } = request.params;
+
+ try {
+ // Parse site ID
+ const siteId = parseInt(site);
+ if (isNaN(siteId)) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+
+ // Check user access to site
+ const userHasAccessToSite = await getUserHasAccessToSite(request, site);
+ if (!userHasAccessToSite) {
+ return reply.status(403).send({ error: "Forbidden" });
+ }
+
+ // Check if session replay exists
+ const sessionReplayQueryService = new SessionReplayQueryService();
+ const metadata = await sessionReplayQueryService.getSessionReplayMetadata(siteId, sessionId);
+
+ if (!metadata) {
+ return reply.status(404).send({ error: "Session replay not found" });
+ }
+
+ // Delete the session replay
+ await sessionReplayQueryService.deleteSessionReplay(siteId, sessionId);
+
+ return reply.status(200).send({ success: true });
+ } catch (error) {
+ console.error("Error deleting session replay:", error);
+ return reply.status(500).send({ error: "Failed to delete session replay" });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 9fb6082f2..6ec87129a 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -45,6 +45,7 @@ import { getConfig } from "./api/getConfig.js";
import { getSessionReplayEvents } from "./api/sessionReplay/getSessionReplayEvents.js";
import { getSessionReplays } from "./api/sessionReplay/getSessionReplays.js";
import { recordSessionReplay } from "./api/sessionReplay/recordSessionReplay.js";
+import { deleteSessionReplay } from "./api/sessionReplay/deleteSessionReplay.js";
import { addSite } from "./api/sites/addSite.js";
import { updateSiteConfig } from "./api/sites/updateSiteConfig.js";
import { deleteSite } from "./api/sites/deleteSite.js";
@@ -346,6 +347,7 @@ server.get("/api/performance/by-dimension/:site", getPerformanceByDimension);
server.post("/api/session-replay/record/:site", recordSessionReplay);
server.get("/api/session-replay/list/:site", getSessionReplays);
server.get("/api/session-replay/:sessionId/:site", getSessionReplayEvents);
+server.delete("/api/session-replay/:sessionId/:site", deleteSessionReplay);
// Administrative
server.get("/api/config", getConfig);
diff --git a/server/src/services/replay/sessionReplayQueryService.ts b/server/src/services/replay/sessionReplayQueryService.ts
index fdd04997c..bf16d3777 100644
--- a/server/src/services/replay/sessionReplayQueryService.ts
+++ b/server/src/services/replay/sessionReplayQueryService.ts
@@ -249,7 +249,7 @@ export class SessionReplayQueryService {
SELECT *
FROM session_replay_metadata
FINAL
- WHERE site_id = {siteId:UInt16}
+ WHERE site_id = {siteId:UInt16}
AND session_id = {sessionId:String}
LIMIT 1
`,
@@ -260,4 +260,57 @@ export class SessionReplayQueryService {
const results = await processResults<SessionReplayMetadata>(result);
return results[0] || null;
}
+
+ /**
+ * Delete a session replay and all associated data
+ * This includes:
+ * - Events from session_replay_events table
+ * - Metadata from session_replay_metadata table
+ * - R2 stored data (if enabled)
+ */
+ async deleteSessionReplay(siteId: number, sessionId: string): Promise<void> {
+ // First, get all R2 keys for this session if R2 is enabled
+ if (r2Storage.isEnabled()) {
+ try {
+ const r2KeysResult = await clickhouse.query({
+ query: `
+ SELECT DISTINCT event_data_key
+ FROM session_replay_events
+ WHERE site_id = {siteId:UInt16}
+ AND session_id = {sessionId:String}
+ AND event_data_key IS NOT NULL
+ `,
+ query_params: { siteId, sessionId },
+ format: "JSONEachRow",
+ });
+
+ const r2Keys = await processResults<{ event_data_key: string }>(r2KeysResult);
+
+ // Delete all R2 batches in parallel
+ await Promise.all(r2Keys.map((row) => r2Storage.deleteBatch(row.event_data_key)));
+ } catch (error) {
+ console.error(`Failed to delete R2 data for session ${sessionId}:`, error);
+ // Continue with ClickHouse deletion even if R2 fails
+ }
+ }
+
+ // Delete from ClickHouse tables
+ await clickhouse.command({
+ query: `
+ DELETE FROM session_replay_events
+ WHERE site_id = {siteId:UInt16}
+ AND session_id = {sessionId:String}
+ `,
+ query_params: { siteId, sessionId },
+ });
+
+ await clickhouse.command({
+ query: `
+ DELETE FROM session_replay_metadata
+ WHERE site_id = {siteId:UInt16}
+ AND session_id = {sessionId:String}
+ `,
+ query_params: { siteId, sessionId },
+ });
+ }
}