Skip to content
Niko Table

API Request Logs

A developer request log with 5,000 virtualized rows, live error rate and p95 latency, method, status class and region filters, a latency slider, and a details panel with a response preview.

Built only from Niko Table pieces and shadcn/ui components. Install it, then swap the sample data for your own.

Installation

pnpm dlx shadcn@latest add @niko-table/request-logs-table

Preview

npx shadcn@latest add @niko-table/request-logs-table
request-logs-table.tsx
"use client"
import * as React from "react"
import { DataTableRoot } from "@/components/niko-table/core/data-table-root"
import { DataTable } from "@/components/niko-table/core/data-table"
import {
DataTableVirtualizedBody,
DataTableVirtualizedEmptyBody,
DataTableVirtualizedHeader,
} from "@/components/niko-table/core/data-table-virtualized-structure"
import { useDataTable } from "@/components/niko-table/core/data-table-context"
import { DataTableColumnHeader } from "@/components/niko-table/components/data-table-column-header"
import { DataTableColumnTitle } from "@/components/niko-table/components/data-table-column-title"
import { DataTableColumnSortMenu } from "@/components/niko-table/components/data-table-column-sort"
import { DataTableToolbarSection } from "@/components/niko-table/components/data-table-toolbar-section"
import { DataTableSearchFilter } from "@/components/niko-table/components/data-table-search-filter"
import { DataTableFacetedFilter } from "@/components/niko-table/components/data-table-faceted-filter"
import { DataTableSliderFilter } from "@/components/niko-table/components/data-table-slider-filter"
import { DataTableClearFilter } from "@/components/niko-table/components/data-table-clear-filter"
import { DataTableViewMenu } from "@/components/niko-table/components/data-table-view-menu"
import {
DataTableEmptyDescription,
DataTableEmptyFilteredMessage,
DataTableEmptyIcon,
DataTableEmptyMessage,
DataTableEmptyTitle,
} from "@/components/niko-table/components/data-table-empty-state"
import {
DataTableRowMenuScope,
RowMenuItem,
useDataTableRow,
} from "@/components/niko-table/components/data-table-row-menu"
import { DataTableRowContextMenuSlot } from "@/components/niko-table/components/data-table-row-context-menu-slot"
import type { DataTableColumnDef } from "@/components/niko-table/types"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/niko-table/primitives/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/niko-table/primitives/dropdown-menu"
import { MoreHorizontal, ScrollText, SearchX } from "lucide-react"
import { cn } from "@/lib/utils"
import {
methodOptions,
regionOptions,
requestLogs,
statusClassOptions,
type RequestLog,
} from "./logs-data"
import {
formatTime,
methodStyle,
percentile95,
statusStyle,
} from "./logs-format"
import { LogSheet } from "./log-sheet"
/** Latency at which the bar in the latency column is full. */
const BAR_MAX_MS = 1000
// Row height = cell p-2 (16px) + tallest cell (size-6 kebab, 24px) + 1px border-b. Change one, change all.
const ROW_HEIGHT = 41
type Actions = {
view: (log: RequestLog) => void
copyId: (log: RequestLog) => void
}
/*
* Row actions: one small piece per action, each reading its row from context.
* `RequestLogsTable` composes them into ONE fragment that both the "⋯"
* dropdown and the right-click menu render.
*/
function ViewDetailsItem({ view }: Pick<Actions, "view">) {
const log = useDataTableRow<RequestLog>()
return <RowMenuItem onClick={() => view(log)}>View details</RowMenuItem>
}
function CopyRequestIdItem({ copyId }: Pick<Actions, "copyId">) {
const log = useDataTableRow<RequestLog>()
return <RowMenuItem onClick={() => copyId(log)}>Copy request ID</RowMenuItem>
}
function FilterByPathItem({
onFiltered,
}: {
onFiltered: (path: string) => void
}) {
const log = useDataTableRow<RequestLog>()
const { table } = useDataTable<RequestLog>()
return (
<RowMenuItem
disabled={table.state.globalFilter === log.path}
onClick={() => {
table.setGlobalFilter(log.path)
onFiltered(log.path)
}}
>
Filter by this path
</RowMenuItem>
)
}
function sortableHeader() {
return (
<DataTableColumnHeader>
<DataTableColumnTitle />
<DataTableColumnSortMenu />
</DataTableColumnHeader>
)
}
function useLogColumns(rowMenu: React.ReactNode) {
return React.useMemo<DataTableColumnDef<RequestLog>[]>(
() => [
{
accessorKey: "id",
// Hidden: lets the search box match request IDs too.
meta: { label: "Request ID" },
enableHiding: false,
},
{
accessorKey: "timestamp",
meta: { label: "Time" },
size: 130,
header: sortableHeader,
enableGlobalFilter: false,
cell: ({ row }) => (
<span className="font-mono text-xs whitespace-nowrap text-muted-foreground tabular-nums">
{formatTime(row.original.timestamp)}
</span>
),
},
{
accessorKey: "method",
meta: { label: "Method", options: methodOptions },
size: 90,
header: sortableHeader,
enableColumnFilter: true,
enableGlobalFilter: false,
cell: ({ row }) => (
<Badge
variant="outline"
className={cn(
"border-0 font-mono text-[11px]",
methodStyle[row.original.method],
)}
>
{row.original.method}
</Badge>
),
},
{
accessorKey: "path",
meta: { label: "Path" },
size: 320,
header: sortableHeader,
cell: ({ row }) => (
<span className="block max-w-xs truncate font-mono text-xs">
{row.original.path}
</span>
),
},
{
accessorKey: "status",
meta: { label: "Status" },
size: 80,
header: sortableHeader,
enableGlobalFilter: false,
cell: ({ row }) => (
<span
className={cn(
"font-mono text-xs font-medium tabular-nums",
statusStyle(row.original.status),
)}
>
{row.original.status}
</span>
),
},
{
id: "statusClass",
// Hidden: backs the Status class filter (2xx / 4xx / 5xx).
accessorFn: log => log.statusClass,
meta: { label: "Status class", options: statusClassOptions },
enableColumnFilter: true,
enableHiding: false,
enableGlobalFilter: false,
},
{
accessorKey: "latencyMs",
meta: { label: "Latency", unit: "ms", variant: "range" },
size: 170,
header: sortableHeader,
enableColumnFilter: true,
enableGlobalFilter: false,
cell: ({ row }) => {
const ms = row.original.latencyMs
return (
<span className="flex items-center gap-2">
<span className="w-14 text-right font-mono text-xs tabular-nums">
{ms} ms
</span>
<span
className="h-1.5 w-16 overflow-hidden rounded-full bg-muted"
aria-hidden="true"
>
<span
className={cn(
"block h-full rounded-full",
ms > 500 ? "bg-warning" : "bg-primary",
)}
style={{
width: `${Math.min(100, (ms / BAR_MAX_MS) * 100)}%`,
}}
/>
</span>
</span>
)
},
},
{
accessorKey: "region",
meta: { label: "Region", options: regionOptions },
size: 90,
header: sortableHeader,
enableColumnFilter: true,
enableGlobalFilter: false,
cell: ({ row }) => (
<span className="font-mono text-xs text-muted-foreground">
{row.original.region}
</span>
),
},
{
id: "actions",
size: 56,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<div className="flex justify-end">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-6"
aria-label={`Open actions for request ${row.original.id}`}
>
<MoreHorizontal className="size-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DataTableRowMenuScope row={row.original} surface="dropdown">
{rowMenu}
</DataTableRowMenuScope>
</DropdownMenuContent>
</DropdownMenu>
</div>
),
},
],
[rowMenu],
)
}
function Stat({
label,
value,
tone,
}: {
label: string
value: string
tone?: string
}) {
return (
<div className="flex flex-col gap-0.5 rounded-lg border bg-background px-3 py-2">
<span className="text-xs text-muted-foreground">{label}</span>
<span className={cn("text-base font-semibold tabular-nums", tone)}>
{value}
</span>
</div>
)
}
/** Totals for the requests that match the current filters. */
function LogsSummary() {
const { table } = useDataTable<RequestLog>()
const rows = table.getFilteredRowModel().rows
const { errorRate, p95 } = React.useMemo(() => {
const logs = rows.map(row => row.original)
const errors = logs.filter(log => log.status >= 400).length
return {
errorRate: logs.length ? (errors / logs.length) * 100 : 0,
p95: percentile95(logs.map(log => log.latencyMs)),
}
}, [rows])
return (
<div className="grid grid-cols-3 gap-2">
<Stat label="Requests" value={rows.length.toLocaleString("en-US")} />
<Stat
label="Error rate"
value={`${errorRate.toFixed(1)}%`}
tone={errorRate >= 10 ? "text-destructive" : undefined}
/>
<Stat label="p95 latency" value={`${p95} ms`} />
</div>
)
}
export default function RequestLogsTable() {
const [viewing, setViewing] = React.useState<RequestLog | null>(null)
const [lastAction, setLastAction] = React.useState("")
const actions = React.useMemo(
() => ({
view: (log: RequestLog) => setViewing(log),
copyId: (log: RequestLog) => {
void navigator.clipboard?.writeText(log.id)
setLastAction(`Copied ${log.id}`)
},
}),
[],
)
// The row actions, composed ONCE and mounted in both the "⋯" dropdown and
// the right-click menu.
const rowMenu = React.useMemo(
() => (
<>
<ViewDetailsItem view={actions.view} />
<CopyRequestIdItem copyId={actions.copyId} />
<FilterByPathItem
onFiltered={path => setLastAction(`Filtered to ${path}`)}
/>
</>
),
[actions],
)
const columns = useLogColumns(rowMenu)
return (
<div className="w-full rounded-xl border bg-card p-4 text-card-foreground shadow-sm">
<DataTableRoot
data={requestLogs}
columns={columns}
getRowId={log => log.id}
initialState={{ columnVisibility: { id: false, statusClass: false } }}
>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-0.5">
<h2 className="text-base font-semibold">Request logs</h2>
<p className="text-sm text-muted-foreground">
The last 24 hours, newest first. Click a request for details.
</p>
</div>
<LogsSummary />
<DataTableToolbarSection className="flex-wrap px-0">
<DataTableSearchFilter
placeholder="Search path or request ID..."
className="min-w-48 flex-none sm:w-64"
/>
<DataTableFacetedFilter accessorKey="method" multiple />
<DataTableFacetedFilter accessorKey="statusClass" multiple />
<DataTableFacetedFilter accessorKey="region" multiple />
<DataTableSliderFilter accessorKey="latencyMs" />
<DataTableClearFilter />
<div className="ml-auto">
<DataTableViewMenu />
</div>
</DataTableToolbarSection>
{/* 5,000 rows, but only the visible window is in the DOM. */}
<DataTable height={520} className="rounded-lg border">
<DataTableVirtualizedHeader />
<DataTableVirtualizedBody<RequestLog>
estimateSize={ROW_HEIGHT}
fixedRowHeight
onRowClick={log => setViewing(log)}
>
<DataTableRowContextMenuSlot>
{rowMenu}
</DataTableRowContextMenuSlot>
<DataTableVirtualizedEmptyBody>
<DataTableEmptyMessage>
<DataTableEmptyIcon>
<ScrollText className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>No requests yet</DataTableEmptyTitle>
<DataTableEmptyDescription>
Requests to your API show up here.
</DataTableEmptyDescription>
</DataTableEmptyMessage>
<DataTableEmptyFilteredMessage>
<DataTableEmptyIcon>
<SearchX className="size-12" />
</DataTableEmptyIcon>
<DataTableEmptyTitle>
No matching requests
</DataTableEmptyTitle>
<DataTableEmptyDescription>
Try a different search or clear the filters.
</DataTableEmptyDescription>
</DataTableEmptyFilteredMessage>
</DataTableVirtualizedEmptyBody>
</DataTableVirtualizedBody>
</DataTable>
{lastAction && (
<p className="text-xs text-muted-foreground" aria-live="polite">
{lastAction}
</p>
)}
</div>
</DataTableRoot>
<LogSheet
log={viewing}
onOpenChange={open => !open && setViewing(null)}
/>
</div>
)
}
log-sheet.tsx
"use client"
import * as React from "react"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/niko-table/primitives/button"
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/niko-table/primitives/sheet"
import { Check, Copy } from "lucide-react"
import { cn } from "@/lib/utils"
import type { RequestLog } from "./logs-data"
import {
formatDateTime,
methodStyle,
sampleResponse,
statusStyle,
} from "./logs-format"
function DetailRow({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div className="flex items-center justify-between gap-4 py-2 text-sm">
<dt className="text-muted-foreground">{label}</dt>
<dd className="min-w-0 text-right">{children}</dd>
</div>
)
}
function CopyButton({ value, label }: { value: string; label: string }) {
const [copied, setCopied] = React.useState(false)
return (
<Button
variant="ghost"
size="icon"
className="size-6"
aria-label={label}
onClick={() => {
void navigator.clipboard?.writeText(value)
setCopied(true)
setTimeout(() => setCopied(false), 1500)
}}
>
{copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
</Button>
)
}
/** Side panel with one request's details. Opens on row click. */
export function LogSheet({
log,
onOpenChange,
}: {
log: RequestLog | null
onOpenChange: (open: boolean) => void
}) {
return (
<Sheet open={log !== null} onOpenChange={onOpenChange}>
<SheetContent className="flex w-full flex-col gap-0 sm:max-w-lg">
{log && (
<>
<SheetHeader className="border-b">
<SheetTitle className="flex items-center gap-2">
<Badge
variant="outline"
className={cn("border-0 font-mono", methodStyle[log.method])}
>
{log.method}
</Badge>
<span className="truncate font-mono text-sm">{log.path}</span>
</SheetTitle>
<SheetDescription>Request {log.id}</SheetDescription>
</SheetHeader>
<div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">
<dl className="divide-y">
<DetailRow label="Request ID">
<span className="flex items-center justify-end gap-1 font-mono text-xs">
{log.id}
<CopyButton value={log.id} label="Copy request ID" />
</span>
</DetailRow>
<DetailRow label="Status">
<span
className={cn(
"font-medium tabular-nums",
statusStyle(log.status),
)}
>
{log.status}
</span>
</DetailRow>
<DetailRow label="Latency">
<span className="tabular-nums">{log.latencyMs} ms</span>
</DetailRow>
<DetailRow label="Region">
<span className="font-mono">{log.region}</span>
</DetailRow>
<DetailRow label="User agent">
<span className="font-mono text-xs">{log.userAgent}</span>
</DetailRow>
<DetailRow label="Timestamp">
<span className="font-mono text-xs tabular-nums">
{formatDateTime(log.timestamp)}
</span>
</DetailRow>
</dl>
{log.error && (
<p
role="alert"
className="rounded-md border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive"
>
{log.error}
</p>
)}
<section className="flex flex-col gap-2">
<h3 className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Response body
</h3>
<pre className="overflow-x-auto rounded-md border bg-muted/40 p-3 font-mono text-xs">
{JSON.stringify(sampleResponse(log), null, 2)}
</pre>
</section>
</div>
</>
)}
</SheetContent>
</Sheet>
)
}
logs-format.ts
import type { HttpMethod, RequestLog } from "./logs-data"
/** "14:03:22.481" (UTC, so the sample reads the same everywhere). */
export function formatTime(timestamp: number) {
return new Date(timestamp).toISOString().slice(11, 23)
}
export function formatDateTime(timestamp: number) {
return `${new Date(timestamp).toISOString().slice(0, 10)} ${formatTime(timestamp)} UTC`
}
export const methodStyle: Record<HttpMethod, string> = {
GET: "bg-muted text-muted-foreground",
POST: "bg-success/15 text-success",
PATCH: "bg-warning/15 text-warning",
DELETE: "bg-destructive/15 text-destructive",
}
export function statusStyle(status: number) {
if (status >= 500) return "text-destructive"
if (status >= 400) return "text-warning"
return "text-success"
}
/** The 95th percentile of the given numbers (nearest rank). */
export function percentile95(values: number[]) {
if (values.length === 0) return 0
const sorted = Float64Array.from(values).sort()
return sorted[Math.ceil(sorted.length * 0.95) - 1] ?? 0
}
/** A made-up response body for the details panel. */
export function sampleResponse(log: RequestLog) {
if (log.error) {
return {
error: { code: log.status, message: log.error, request_id: log.id },
}
}
if (log.status === 204) return null
const last = log.path.split("/").pop() ?? ""
const isId = last.includes("_") || last === "me"
if (log.method === "GET" && !isId) {
return { object: "list", data: [], has_more: false }
}
return {
id: isId ? last : log.id.replace("req_", "obj_"),
object: log.path.split("/")[2]?.replace(/s$/, ""),
livemode: true,
created: Math.floor(log.timestamp / 1000),
}
}
logs-data.ts
export type HttpMethod = "GET" | "POST" | "PATCH" | "DELETE"
export type StatusClass = "2xx" | "4xx" | "5xx"
export type RequestLog = {
id: string
/** Milliseconds since the epoch. */
timestamp: number
method: HttpMethod
path: string
status: number
statusClass: StatusClass
latencyMs: number
region: string
userAgent: string
/** Set for 4xx and 5xx only. */
error: string | null
}
/** Fixed "now" for the sample data, so the log never drifts. */
export const NOW = Date.UTC(2026, 10, 2, 15, 0, 0, 0)
export const LOG_COUNT = 5000
export const methodOptions = [
{ label: "GET", value: "GET" },
{ label: "POST", value: "POST" },
{ label: "PATCH", value: "PATCH" },
{ label: "DELETE", value: "DELETE" },
]
export const statusClassOptions = [
{ label: "2xx Success", value: "2xx" },
{ label: "4xx Client error", value: "4xx" },
{ label: "5xx Server error", value: "5xx" },
]
export const regionOptions = [
{ label: "iad1 (Virginia)", value: "iad1" },
{ label: "fra1 (Frankfurt)", value: "fra1" },
{ label: "sin1 (Singapore)", value: "sin1" },
{ label: "syd1 (Sydney)", value: "syd1" },
]
/**
* Sample data, generated rather than hand-written. A seeded PRNG (mulberry32)
* keeps it random-looking but identical on every render. Swap `requestLogs`
* for your own rows.
*/
function seededRandom(seed: number) {
let a = seed
return () => {
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const random = seededRandom(20261102)
const pick = <T>(items: readonly T[]): T =>
items[Math.floor(random() * items.length)] as T
const hex = (length: number) =>
Array.from({ length }, () => Math.floor(random() * 16).toString(16)).join("")
/** Weighted routes: the heavier the weight, the more often it is called. */
const routes: { method: HttpMethod; path: string; weight: number }[] = [
{ method: "GET", path: "/v1/users/me", weight: 18 },
{ method: "GET", path: "/v1/projects", weight: 12 },
{ method: "GET", path: "/v1/projects/:id", weight: 14 },
{ method: "GET", path: "/v1/invoices", weight: 8 },
{ method: "GET", path: "/v1/webhooks/:id/deliveries", weight: 6 },
{ method: "GET", path: "/v1/usage", weight: 7 },
{ method: "POST", path: "/v1/projects", weight: 3 },
{ method: "POST", path: "/v1/invoices", weight: 4 },
{ method: "POST", path: "/v1/webhooks/:id/replay", weight: 3 },
{ method: "POST", path: "/v1/events", weight: 12 },
{ method: "PATCH", path: "/v1/projects/:id", weight: 5 },
{ method: "PATCH", path: "/v1/users/me", weight: 3 },
{ method: "DELETE", path: "/v1/projects/:id", weight: 1 },
{ method: "DELETE", path: "/v1/webhooks/:id", weight: 1 },
]
const totalWeight = routes.reduce((sum, route) => sum + route.weight, 0)
function pickRoute() {
let n = random() * totalWeight
for (const route of routes) {
n -= route.weight
if (n < 0) return route
}
return routes[0] as (typeof routes)[number]
}
const userAgents = [
"ledgerkit-node/3.4.1",
"ledgerkit-node/3.5.0",
"ledgerkit-py/2.11.0",
"ledgerkit-go/1.8.2",
"ledgerkit-ruby/4.0.3",
"curl/8.7.1",
"okhttp/4.12.0",
]
const regions = ["iad1", "iad1", "iad1", "fra1", "fra1", "sin1", "syd1"]
const errors: Record<number, string> = {
400: "Invalid JSON body",
401: "Missing or expired API key",
403: "Key does not have access to this project",
404: "Resource not found",
409: "A resource with this name already exists",
422: "Field `currency` must be a 3-letter code",
429: "Rate limit exceeded, retry in 12s",
500: "Internal error while handling the request",
502: "Upstream service returned an invalid response",
503: "Service temporarily unavailable",
}
function pickStatus(method: HttpMethod): number {
const roll = random()
if (roll < 0.012) return pick([500, 500, 502, 503])
if (roll < 0.05) return 429
if (roll < 0.1) {
if (method === "POST") return pick([400, 401, 409, 422, 422])
if (method === "PATCH") return pick([400, 404, 409, 422])
return pick([401, 403, 404, 404])
}
if (method === "POST") return pick([200, 201, 201])
if (method === "DELETE") return 204
return 200
}
/** Skewed: most requests are fast, a few take much longer. */
function pickLatency(method: HttpMethod, status: number) {
const base = method === "GET" ? 28 : 55
const tail = Math.pow(random(), 3) * 900
const spike = random() < 0.03 ? 600 + random() * 1800 : 0
const slow = status >= 500 ? 400 : 0
return Math.round(base + random() * 40 + tail + spike + slow)
}
function generate(): RequestLog[] {
const day = 24 * 60 * 60 * 1000
const times = Array.from({ length: LOG_COUNT }, () =>
Math.floor(NOW - random() * day),
).sort((a, b) => b - a)
return times.map(timestamp => {
const route = pickRoute()
const status = pickStatus(route.method)
const statusClass: StatusClass =
status >= 500 ? "5xx" : status >= 400 ? "4xx" : "2xx"
return {
id: `req_${hex(12)}`,
timestamp,
method: route.method,
path: route.path.replace(
":id",
() => `${route.path.includes("/webhooks") ? "wh" : "prj"}_${hex(6)}`,
),
status,
statusClass,
latencyMs: pickLatency(route.method, status),
region: pick(regions),
userAgent: pick(userAgents),
error: errors[status] ?? null,
}
})
}
/** 5,000 requests from the last 24 hours, newest first. Built once at load. */
export const requestLogs: RequestLog[] = generate()

Usage

The files land in components/request-logs-table/. Render the block anywhere:

import APIRequestLogs from "@/components/request-logs-table/request-logs-table"
export default function Page() {
return <APIRequestLogs />
}

Then replace the generated rows in logs-data.ts with your own data, or load it from your API and pass it in.