Read Supabase from a Cloudflare Worker with plain fetch (no SDK)
Abstract
A small typed client for Supabase's REST API: headers, filters, input validation, timeouts and error handling, tested with a fake fetch.
Supabase exposes every table over a REST API (PostgREST), which means a Cloudflare Worker can read your data with nothing but fetch. This tutorial builds a small read-only client in TypeScript: no SDK, a few dozen lines, with validation, a timeout and tidy errors. This is the same approach this site uses to read its posts.
The code below was type-checked with TypeScript 7.0.2 in strict mode and run on Node 24 with a fake fetch. It was not run against a live database in the tutorial; the same query shapes are what this site runs in production, and for example /papers?tag=tutorial is served by them.
Why skip the SDK
A Worker that only reads rows needs one HTTP call. An SDK adds a dependency, bundle size and an API to learn. PostgREST filters are plain query parameters, so a thin wrapper is enough. If you need auth flows or realtime, use the SDK. For reading a blog, you do not.
The client
export type Post = { slug: string; title: string; tags: string[] };
export class DbError extends Error {}
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
type Config = { url: string; anonKey: string };
export function createDb(cfg: Config, fetchFn: typeof fetch = fetch, timeoutMs = 5000) {
const headers: Record<string, string> = { apikey: cfg.anonKey, accept: 'application/json' };
// Legacy anon keys are JWTs and also go in Authorization; newer publishable keys are not JWTs.
if (cfg.anonKey.startsWith('eyJ')) headers.authorization = `Bearer ${cfg.anonKey}`;
async function get<T>(query: URLSearchParams): Promise<T> {
let res: Response;
try {
res = await fetchFn(`${cfg.url}/rest/v1/posts?${query}`, {
headers,
signal: AbortSignal.timeout(timeoutMs),
});
} catch {
throw new DbError('request failed or timed out');
}
if (!res.ok) throw new DbError(`database responded ${res.status}`);
return (await res.json()) as T;
}
return {
async listPosts(tag?: string): Promise<Post[]> {
if (tag !== undefined && !SLUG_RE.test(tag)) return [];
const q = new URLSearchParams({
select: 'slug,title,tags',
published: 'eq.true',
order: 'published_at.desc',
limit: '20',
});
if (tag) q.set('tags', `cs.{${tag}}`);
return get<Post[]>(q);
},
async getPost(slug: string): Promise<Post | null> {
if (!SLUG_RE.test(slug)) return null;
const q = new URLSearchParams({
select: 'slug,title,tags',
published: 'eq.true',
slug: `eq.${slug}`,
limit: '1',
});
return (await get<Post[]>(q))[0] ?? null;
},
};
}
How the request is built
The URL is <project url>/rest/v1/<table> followed by a query string. Each parameter is a filter or an option:
select=slug,title,tagspicks columns.published=eq.truefilters rows where the column equals true.order=published_at.descsorts newest first.limit=20caps the result.tags=cs.{demo}usescs, “contains”, on an array column, so it matches posts whosetagsarray includesdemo.slug=eq.hellofetches one row by slug.
The apikey header carries the project’s public key. Older Supabase keys are JWTs and are also sent as a bearer token; the eyJ prefix check handles both styles. Use placeholders in your own code samples and keep the key out of your repository; this site’s wrangler.toml holds only the project URL.
Validate before you build the filter
tag and slug end up inside a filter string, so the client checks them first with a strict pattern. Anything that is not lowercase words joined by hyphens never reaches the database. The test:
bad tag -> [] calls so far: 2
bad slug -> null calls so far: 2
An input like x,or=(published.eq.false) for a tag returns an empty list, and a slug of ../etc returns null, and in both cases no request was made (the counter stays at 2). Row-level security protects the data regardless, as covered in the security tutorial, but there is no reason to send odd input at all.
Timeouts and errors
AbortSignal.timeout cancels a request that takes too long, the same technique used in the retry tutorial. Both network failures and non-2xx responses are turned into one DbError, so a route handler can catch it and return a clean 503 instead of leaking a stack trace. The tests covered both:
true database responded 503
true request failed or timed out
What the test showed
With a fake fetch that records its calls:
1 post(s)
https://example.supabase.co/rest/v1/posts?select=slug,title,tags&published=eq.true&order=published_at.desc&limit=20
https://example.supabase.co/rest/v1/posts?select=slug,title,tags&published=eq.true&order=published_at.desc&limit=20&tags=cs.{demo}
headers: apikey,accept
jwt headers: apikey,accept,authorization
The URLs above are shown decoded for readability. On the wire, URLSearchParams percent-encodes characters such as the braces.
Injecting fetchFn as a parameter is what made this testable without a network. A practical note from writing the test: Node’s AbortSignal.timeout does not keep an otherwise idle process alive, so a fake request that never resolves can exit silently. Add a keep-alive timer in the test; a real socket would not need it.
Conclusion
A read path to Supabase is a header, a URL and a few filters. Validate the values you interpolate, cap the time you wait, and wrap failures in one error type.[1]
Reviewer 2 asks why the client has no retries. The authors point to the other tutorial and a strong desire to keep this one short. ↩︎