Postgres Dashboard Without Handing Over Your Database
A Postgres dashboard usually starts the same way: the numbers you want are sitting in your own tables, and every tool that offers to chart them asks for a connection string first. This page builds a PostgreSQL dashboard the other way round — signups today, revenue for the last seven days and your top accounts — without giving anyone your database.
dashboardbase does not connect to Postgres. There is no database connector and no "paste your connection string" field. You write a small endpoint that runs one parameterised SQL query and returns the JSON shape below, and dashboardbase renders it. Your credentials stay where they already are: in your backend's environment.
That is the whole argument for doing it this way. Every BI tool answers "dashboard for PostgreSQL" by asking for read access to production. A security review then has to ask who else can use that access, from where, and what happens when the tool is breached. Here, the only thing that leaves your network is the JSON your endpoint chose to return.
What you'll build
- Signups today (KPI) — new users since local midnight, against yesterday by this time
- Revenue, last 7 days (line chart) — paid orders per day, with the total and the change against the week before
- Top accounts this month (table) — who your revenue actually comes from
One query per widget, one route per query. It works the same whether the database runs on RDS, Supabase, Neon or a server under someone's desk, because the only thing that talks to it is your own code.
Prerequisites
- A Postgres database your backend can already reach (the examples assume
users,ordersandaccountstables; swap in your own) - A read-only database role for the dashboard (set up under "Securing the endpoint" below)
- A backend you can deploy a route to. The examples use Node.js with the
pglibrary; the JSON is the same from Python, Go, Ruby or anything else - A dashboardbase account
Step 1: Signups today **
The KPI widget takes one headline number and a trend badge. This is the contract:
{
"title": "Signups today",
"actions": [
{
"title": "View users",
"type": "link",
"url": "https://admin.example.com/users"
}
],
"data": {
"header": {
"title": "42",
"subtitle": "vs yesterday by this time",
"badge": {
"text": "+7",
"icon": "ArrowUp",
"color": "Success"
}
}
}
}Paste that into the free endpoint validator and it shows you the widget, no account needed. It's the quickest way to find out whether a payload renders before you write the handler.
You don't have to write the handler by hand either. The free dashboardbase Skill teaches Claude Code, Cursor or any skills-capable agent this contract, so it scaffolds a correctly shaped endpoint around your query. If you'd rather not set up an agent, the widget editor generates a prompt you can paste into whatever AI tool you already use. Either way it's a draft you review and run yourself.
The setup shared by every route on this page — one small pool, one time zone:
import express from 'express'
import pg from 'pg'
const app = express()
// A dedicated connection string for the read-only role, not the app's own.
const pool = new pg.Pool({
connectionString: process.env.DASHBOARD_DATABASE_URL,
max: 3,
})
// "Today" means today where your business is, not in UTC.
const TZ = 'America/New_York'And the signups route. The query compares today with yesterday up to the same time of day, so the badge isn't red every morning:
app.get('/dashboard/signups-today', async (req, res) => {
const { rows } = await pool.query(
`WITH bounds AS (
SELECT date_trunc('day', now() AT TIME ZONE $1::text) AS local_midnight
)
SELECT
count(*) FILTER (WHERE u.created_at >= b.local_midnight AT TIME ZONE $1::text) AS today,
count(*) FILTER (WHERE u.created_at < b.local_midnight AT TIME ZONE $1::text
AND u.created_at < now() - interval '1 day') AS yesterday
FROM users u, bounds b
WHERE u.created_at >= (b.local_midnight - interval '1 day') AT TIME ZONE $1::text`,
[TZ]
)
// count(*) is a bigint, and pg returns bigints as strings.
const today = Number(rows[0].today)
const delta = today - Number(rows[0].yesterday)
res.json({
title: 'Signups today',
actions: [
{
title: 'View users',
type: 'link',
url: 'https://admin.example.com/users',
},
],
data: {
header: {
title: String(today),
subtitle: 'vs yesterday by this time',
badge: {
text: `${delta >= 0 ? '+' : ''}${delta}`,
icon: delta >= 0 ? 'ArrowUp' : 'ArrowDown',
color: delta >= 0 ? 'Success' : 'Danger',
},
},
},
})
})Paste the route's URL into a KPI widget and the first number is live.
Step 2: Revenue for the last 7 days **
A line chart takes labels and datasets, where every data point is an object with a value. The header on top carries the total and the trend:
{
"title": "Revenue",
"actions": [
{
"title": "View orders",
"type": "link",
"url": "https://admin.example.com/orders"
}
],
"data": {
"header": {
"title": "$18,240",
"subtitle": "Last 7 days",
"badge": {
"text": "+12%",
"icon": "ArrowUp",
"color": "Success"
}
},
"labels": [
"Thu",
"Fri",
"Sat",
"Sun",
"Mon",
"Tue",
"Wed"
],
"datasets": [
{
"data": [
{
"value": 2410
},
{
"value": 3020
},
{
"value": 1980
},
{
"value": 1650
},
{
"value": 2890
},
{
"value": 3170
},
{
"value": 3120
}
],
"label": "Revenue"
}
]
}
}The query that feeds it uses generate_series so a day with no orders still shows up as zero instead of silently disappearing from the chart:
const usd = (amount) =>
new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(amount)
app.get('/dashboard/revenue-7d', async (req, res) => {
const daily = await pool.query(
`WITH days AS (
SELECT generate_series(
date_trunc('day', now() AT TIME ZONE $1::text) - interval '6 days',
date_trunc('day', now() AT TIME ZONE $1::text),
interval '1 day'
) AS day
)
SELECT to_char(d.day, 'Dy') AS label, coalesce(sum(o.total), 0) AS revenue
FROM days d
LEFT JOIN orders o
ON o.status = 'paid'
AND o.created_at >= d.day AT TIME ZONE $1::text
AND o.created_at < (d.day + interval '1 day') AT TIME ZONE $1::text
GROUP BY d.day
ORDER BY d.day`,
[TZ]
)
const previous = await pool.query(
`SELECT coalesce(sum(total), 0) AS revenue
FROM orders
WHERE status = 'paid'
AND created_at >= (date_trunc('day', now() AT TIME ZONE $1::text) - interval '13 days') AT TIME ZONE $1::text
AND created_at < (date_trunc('day', now() AT TIME ZONE $1::text) - interval '6 days') AT TIME ZONE $1::text`,
[TZ]
)
// sum() over a numeric column is numeric, which pg also returns as a string.
const values = daily.rows.map((row) => Number(row.revenue))
const total = values.reduce((sum, value) => sum + value, 0)
const before = Number(previous.rows[0].revenue)
const change = before === 0 ? 0 : Math.round(((total - before) / before) * 100)
res.json({
title: 'Revenue',
actions: [
{
title: 'View orders',
type: 'link',
url: 'https://admin.example.com/orders',
},
],
data: {
header: {
title: usd(total),
subtitle: 'Last 7 days',
badge: {
text: `${change >= 0 ? '+' : ''}${change}%`,
icon: change >= 0 ? 'ArrowUp' : 'ArrowDown',
color: change >= 0 ? 'Success' : 'Danger',
},
},
labels: daily.rows.map((row) => row.label),
datasets: [
{
data: values.map((value) => ({ value: Math.round(value) })),
label: 'Revenue',
},
],
},
})
})The labels come out of SQL with to_char on purpose. A timestamp column without a time zone arrives in Node as a Date in the server's zone, which is one more place for a day to shift.
Step 3: Top accounts this month **
The table widget takes columns with widths and rows of cells. Every cell is an object, never a bare string, so a cell can carry a link or a badge:
{
"title": "Top accounts this month",
"actions": [
{
"title": "All accounts",
"type": "link",
"url": "https://admin.example.com/accounts"
}
],
"data": {
"columns": [
{ "text": "Account", "width": 45 },
{ "text": "Plan", "width": 30 },
{ "text": "Revenue", "width": 25 }
],
"rows": [
[
{ "text": "Northwind", "link": "https://admin.example.com/accounts/118" },
{ "text": "Business", "badge": { "text": "Business", "color": "Dark" } },
{ "text": "$4,120" }
],
[
{ "text": "Initech", "link": "https://admin.example.com/accounts/342" },
{ "text": "Team", "badge": { "text": "Team", "color": "Success" } },
{ "text": "$2,860" }
]
]
}
}The handler is one GROUP BY:
app.get('/dashboard/top-accounts', async (req, res) => {
const { rows } = await pool.query(
`SELECT a.id, a.name, a.plan, sum(o.total) AS revenue
FROM orders o
JOIN accounts a ON a.id = o.account_id
WHERE o.status = 'paid'
AND o.created_at >= date_trunc('month', now() AT TIME ZONE $1::text) AT TIME ZONE $1::text
GROUP BY a.id, a.name, a.plan
ORDER BY revenue DESC
LIMIT 10`,
[TZ]
)
res.json({
title: 'Top accounts this month',
actions: [
{
title: 'All accounts',
type: 'link',
url: 'https://admin.example.com/accounts',
},
],
data: {
columns: [
{ text: 'Account', width: 45 },
{ text: 'Plan', width: 30 },
{ text: 'Revenue', width: 25 },
],
rows: rows.map((account) => [
{ text: account.name, link: `https://admin.example.com/accounts/${account.id}` },
{ text: account.plan, badge: { text: account.plan, color: 'Success' } },
{ text: usd(Number(account.revenue)) },
]),
},
})
})That's the board. Three routes, three queries, and the only code that knows your schema is code you already own.
Securing the endpoint
This is the section the whole approach exists for, so it has two halves: who may call the endpoint, and what the endpoint may do to the database.
Who may call it. Every dashboardbase workspace has an Endpoint Secret, and dashboardbase sends it as an x-dashboardbase-secret header on every request to your endpoints. You don't wire anything up on our side. Find it under Settings → Secrets → Endpoint Secret (or open app.dashboardbase.com/workspace, which redirects to the active workspace). It proves the call came from dashboardbase; it is not a key for calling us.
import { timingSafeEqual } from 'node:crypto'
// Fail at boot rather than serving your tables to anyone with the URL.
const SECRET = process.env.DASHBOARDBASE_ENDPOINT_SECRET
if (!SECRET) throw new Error('DASHBOARDBASE_ENDPOINT_SECRET is not set')
const KNOWN = Buffer.from(SECRET)
app.use('/dashboard', (req, res, next) => {
const sent = Buffer.from(req.get('x-dashboardbase-secret') ?? '')
if (sent.length !== KNOWN.length || !timingSafeEqual(sent, KNOWN)) {
return res.status(401).json({ error: 'unauthorized' })
}
next()
})Register that middleware before the routes. Rotating the secret keeps the old value working for 24 hours, so a deploy has time to catch up. Custom headers such as Authorization: Bearer … and Basic Auth work on top of it if you want them. When you validate the datasource in the app, dashboardbase also sends one request with every credential stripped and reports what came back: a green "Protected — returns 401 without the secret", or a warning naming the header to check.
What it may do to the database. Give the dashboard its own role, and give that role nothing it doesn't need:
CREATE ROLE dashboard_reader LOGIN PASSWORD 'use-a-generated-one';
ALTER ROLE dashboard_reader SET default_transaction_read_only = on;
ALTER ROLE dashboard_reader SET statement_timeout = '5s';
GRANT CONNECT ON DATABASE app TO dashboard_reader;
GRANT USAGE ON SCHEMA public TO dashboard_reader;
GRANT SELECT ON users, orders, accounts TO dashboard_reader;The GRANTs are the real control: the role can read three tables and nothing else. default_transaction_read_only is a seatbelt, not a lock, because a session can turn it off again; it stops an accident, not an attacker. If a table holds columns the dashboard has no business seeing, grant SELECT on a view that leaves them out instead. And if you have a read replica, point DASHBOARD_DATABASE_URL at that.
Never build SQL from strings. Every value in the queries above goes in as a $1 parameter. dashboardbase sends a plain GET with no user input, but a route you add later might take a query parameter, and a habit is cheaper than an audit.
Common gotchas
count(*)on a big table is a full scan. Counting rows in a recent, indexed range (like "signups today" with an index oncreated_at) is cheap. Counting the whole of a large table on every refresh isn't. For an all-time total, an estimate frompg_class.reltuplesis usually good enough for a wall display, or keep a counter table.numericandbigintarrive as strings. Thepgdriver returns them as strings so it never loses precision. Convert them on purpose, as the handlers above do. For money, that's fine when you're rounding for display. Do the arithmetic in SQL, or in integer cents, if the exact figure matters.- Day boundaries.
date_trunc('day', created_at)on atimestamptzbuckets by the session's time zone, which is usually UTC. Convert withAT TIME ZONEfirst, as above, or your "today" ends at 7 p.m. in New York. - Put a timeout on dashboard queries. A dashboard that refreshes on an interval will happily start the same slow query again before the last one finished.
statement_timeouton the role caps the damage. A failing widget is better than a database under load. - Keep the pool small. Three connections is plenty for a handful of widgets. On serverless platforms, go through your provider's connection pooler (or PgBouncer) instead of opening a connection per request.
- Cache when it's expensive. If a query takes more than a moment, cache the response for a minute. Nobody needs revenue recalculated to the millisecond.
This is not a database monitoring dashboard
Searches for "postgres dashboard" are split. Half the people want what this page builds: the business data in their tables. The other half want the health of the database — connections, cache hit ratio, replication lag, slow queries. For that, a monitoring stack such as Grafana with postgres_exporter, or a dedicated Postgres monitoring tool, is the right call. Those tools read Postgres' own statistics views, and that's their whole job.
dashboardbase isn't the right call either if you want to explore data: writing ad-hoc SQL, slicing and drilling into results. That's what SQL-first BI tools are for. Our Metabase alternatives comparison covers the trade-off, including the one Metabase itself makes: it needs a connection to your database.
Where this approach wins is the case in between: a small set of known numbers your team watches every day, on a laptop, a phone or the office TV, without a third party holding a key to production.
FAQ
Can dashboardbase connect directly to my Postgres database? No, and that's deliberate. dashboardbase only calls HTTPS endpoints you expose and renders the JSON they return. Your connection string never leaves your backend, and nothing on our side can run a query against your database.
Do I have to open my database to the internet? No. The database stays wherever it is. Only your endpoint has to be reachable, and it can refuse every request that doesn't carry your workspace's Endpoint Secret.
Does this work with Supabase, Neon or Amazon RDS? Yes. Anything your backend can query works, because the database is only ever talking to your own code. Use the provider's pooled connection string when your backend is serverless.
Do I have to use Node.js? No. The examples use Node.js and pg, but the JSON contract is the same in every language. The Node.js dashboard guide has more on the Node side, and the stack guides cover Python, Go, Ruby, PHP, Java and .NET.
Next steps
- If your numbers live in more than one place, the same pattern joins them. One endpoint can read Postgres and Stripe and return a single KPI. See the Stripe dashboard for the payments half.
- Building this for the team rather than for yourself? Building an internal dashboard from your own API covers what to put on it and how to keep it private.
- Then point a widget at your first route and see what your own data looks like when someone else does the rendering.
About the third-party code **
The examples on this page were written against the PostgreSQL documentation and the pg library for Node.js. Libraries and drivers change, so treat this code as a starting point and check it against the PostgreSQL documentation and node-postgres before you rely on it. Test every query against a copy of your own schema first.