Add authentication-aware PostgreSQL Row-Level Security to any Node.js application — without adopting a database platform or extra infrastructure.
PostgreSQL already enforces RLS. Most applications still fail at the glue:
- Session identity is set with session-level
SETand leaks across pooled connections. - Queries run as a table owner or superuser and silently bypass RLS.
- Missing context fails open.
- Teams stitch together an ORM, an auth library, and ad-hoc SQL to imitate Supabase.
pg-guard is the portable runtime that takes a verified server-side session, binds it to one transaction on a pooled connection, and lets PostgreSQL enforce the rest.
import { createPgGuard } from "pg-guard";
const guard = createPgGuard({
pool,
runtimeRole: "app_authenticated",
});
const session = await getVerifiedSession(); // your auth library, not pg-guard
const projects = await guard.run(
{
userId: session.user.id,
tenantId: session.activeOrganizationId,
},
async (client) => {
const result = await client.query("select * from projects");
return result.rows;
},
);run() validates context, opens a transaction, switches to a restricted role, sets transaction-local GUCs with parameterized set_config(..., true), runs your callback on that client, then commits or rolls back and releases the connection.
| Layer | MVP |
|---|---|
| Runtime | Node.js 24+ |
| Driver | node-postgres |
| ORM (optional) | Drizzle |
| Auth (optional) | Better Auth, or any verifier |
| Framework (optional) | Next.js App Router |
| Database | Any standard PostgreSQL 16+ (self-hosted VPS, local Docker, managed Postgres) |
You do not need Supabase, Neon-specific extensions, PostgREST, or a hosted gateway.
- pg-guard does not authenticate users. Verify the session first, then map it.
- pg-guard is server-side only. Do not import it in Client Components or browsers.
- PostgreSQL remains the enforcement layer. Policies and
GRANTs are the source of truth. - The package is independent of the database host.
- Administrative connections must never reach browser code.
- RLS does not replace application authorization (quotas, workflows, audit rules).
Identity is transaction-local. A reused pool connection cannot keep the previous user’s role or GUCs. Missing context fails closed. System access is a separate API and a separate pool.
See docs/architecture.md and docs/threat-model.md.
cd examples/next-better-auth-drizzle
cp .env.example .env
pnpm db:up && pnpm db:setup && pnpm db:seed && pnpm devOpen http://localhost:3456. Enter as Acme, try the steal, run the system job, then switch to Globex.
pnpm add pg-guard pg
pnpm pg-guard init --yes --database-client drizzle --auth better-auth --framework next
pnpm drizzle-kit migrateimport { createDrizzleGuard } from "pg-guard/drizzle";
import { createBetterAuthMapper } from "pg-guard/better-auth";
export const toGuardContext = createBetterAuthMapper({
userId: (session) => session.user.id,
tenantId: (session) => session.session.activeOrganizationId,
sessionId: (session) => session.session.id,
roles: (session) => session.user.roles ?? [],
});
export const guard = createDrizzleGuard({
pool,
schema,
runtimeRole: "app_authenticated",
});
const session = await auth.api.getSession({ headers: request.headers });
if (!session) return new Response("Unauthorized", { status: 401 });
return guard.run(toGuardContext(session), async (db) => db.query.projects.findMany());- Not an auth provider, ORM, query gateway, or static RLS analyzer.
- Does not verify cookies or JWTs.
- Cannot stop application code from capturing an unrestricted
dbin a closure. - Does not cover
TRUNCATE/ superuser operations. - Nested
guard.run()is rejected. - Advanced policy review belongs in pgrls.
- Getting started
- PostgreSQL setup
- Drizzle
- Better Auth
- Next.js
- Custom auth
- System operations
- Deployment
- Troubleshooting
- Policy cookbook
- Example app
- Security policy
MIT