Skip to content

feat(postgrest): add URL length validation and timeout protection - #2078

Merged
mandarini merged 5 commits into
masterfrom
fix/postgrest-url-validation
Jan 30, 2026
Merged

mandarini merged 5 commits into
masterfrom
fix/postgrest-url-validation

Conversation

@mandarini

@mandarini mandarini commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

When users create queries with very long field lists (10k+ characters), requests can hang indefinitely instead of returning an error. This occurs because:

  1. PostgREST echoes query parameters back in Content-Location response headers
  2. Large response headers exceed Node's undici parser limits (default 8KB)
  3. Errors during response header parsing may not propagate correctly, causing hangs
  4. No timeout protection exists by default

Solution

This PR implements three defensive changes to prevent indefinite hangs and improve developer experience:

1. URL Length Warning (PostgrestQueryBuilder.ts)

  • Console warning when select parameter exceeds 8000 characters
  • Helps developers identify potential issues before they occur
  • Non-breaking: warning only, doesn't change behavior
// When select string > 8KB, logs:
// "postgrest-js: select parameter is 9889 characters. Very long field lists
//  may cause issues due to HTTP header limits. Consider using views or
//  selecting fewer fields."

2. Timeout Option (PostgrestClient.ts)

  • New optional timeout parameter in constructor
  • Automatically aborts requests after specified duration
  • Properly merges with existing AbortSignals
  • Non-breaking: opt-in via constructor option
const client = new PostgrestClient('https://example.com/rest/v1', {
  timeout: 30000 // 30 second timeout
})

3. Enhanced Error Messages (PostgrestBuilder.ts)

  • AbortError responses now include helpful hints
  • Links timeout to potential root cause when URL is very long
  • Adds PGRST_TIMEOUT error code for easier error handling
// Example error response for timeout with long URL:
{
  error: {
    message: "AbortError: The operation was aborted",
    details: "...",
    hint: "Request was aborted (timeout or manual cancellation). Note: Your request URL is 9889 characters, which may exceed server limits. Consider using views or selecting fewer fields.",
    code: "PGRST_TIMEOUT"
  },
  data: null,
  count: null,
  status: 0,
  statusText: ""
}

Breaking Changes

None. All features are:

  • Opt-in (timeout requires explicit configuration)
  • Additive only (new fields in error responses, console warnings)
  • Preserve existing behavior when not configured

Usage

// Before (still works exactly the same)
const client = new PostgrestClient('https://example.com/rest/v1')

// After (with timeout protection)
const client = new PostgrestClient('https://example.com/rest/v1', {
  timeout: 30000 // optional, prevents indefinite hangs
})

Summary by CodeRabbit

  • New Features
    • Configurable request timeout and configurable URL-length limit (defaults applied) for database requests; client surfaces runtime warnings when URLs are very long.
  • Documentation
    • Constructor/options docs updated to document timeout and URL-length limit settings.
  • Tests
    • New tests covering timeout behavior, long-URL warnings, header-overflow scenarios, and enhanced error messages (unit and integration).

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 29, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@mandarini has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 6 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

Adds optional request timeout support to PostgrestClient (wraps fetch with AbortController), threads a configurable URL length limit through builders, and enhances client-side error objects (AbortError and headers-overflow) with hints and codes; includes tests and TS lib updates.

Changes

Cohort / File(s) Summary
PostgREST client
packages/core/postgrest-js/src/PostgrestClient.ts
Adds timeout?: number option (wraps fetch with AbortController when >0) and exposes urlLengthLimit on the client; passes urlLengthLimit into query/filter builders.
Builder error handling
packages/core/postgrest-js/src/PostgrestBuilder.ts
Adds protected urlLengthLimit and computes request URL length in non-throwing error path; sets contextual hint and code for AbortError and headers-overflow situations, appending URL-length guidance when applicable.
Query builder propagation
packages/core/postgrest-js/src/PostgrestQueryBuilder.ts
Adds public urlLengthLimit and propagates it to PostgrestFilterBuilder for select/insert/upsert/update/delete flows.
Tests (timeout & URL length)
packages/core/postgrest-js/test/timeout-and-url-length.test.ts
New comprehensive tests for timeout behavior, AbortSignal handling, URL-length diagnostics, and HeadersOverflow detection and hinting.
Supabase integration & types
packages/core/supabase-js/src/SupabaseClient.ts, packages/core/supabase-js/src/lib/types.ts
Adds db.timeout?: number and db.urlLengthLimit?: number to Supabase client options and forwards them to PostgrestClient; updates types and examples.
Integration tests
packages/core/supabase-js/test/integration.test.ts
Adds PostgREST timeout configuration tests (appears duplicated in this diff).
TypeScript libs / configs
packages/core/postgrest-js/tsconfig.json, packages/core/postgrest-js/tsconfig.tstyche.json
Adds lib: ["ES2022"] to the PostgREST package tsconfig files.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant App as App / SDK
participant PGC as PostgrestClient
participant Fetch as fetch / network
participant Server as PostgREST
App->>PGC: send request (optional timeout, urlLengthLimit)
alt timeout provided (>0)
PGC->>PGC: create AbortController & timer
PGC->>Fetch: call fetch(..., signal)
else no timeout
PGC->>Fetch: call fetch(...)
end
Fetch-->>PGC: response / error / abort
alt AbortError (signal aborted)
PGC->>PGC: compute URL length, set hint/code (timeout + url-length if long)
PGC->>App: return error with code/hint
else HeadersOverflowError
PGC->>PGC: compute URL length, set hint/code (headers overflow + url-length if long)
PGC->>App: return error with code/hint
else success
PGC->>App: return data
end

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: adding URL length validation and timeout protection to PostgREST, which are the core features introduced across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/postgrest-url-validation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the postgrest-js Related to the postgrest-js library. label Jan 29, 2026
@mandarini mandarini self-assigned this Jan 29, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jan 29, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@supabase/auth-js

npm i https://pkg.pr.new/@supabase/auth-js@2078

@supabase/functions-js

npm i https://pkg.pr.new/@supabase/functions-js@2078

@supabase/postgrest-js

npm i https://pkg.pr.new/@supabase/postgrest-js@2078

@supabase/realtime-js

npm i https://pkg.pr.new/@supabase/realtime-js@2078

@supabase/storage-js

npm i https://pkg.pr.new/@supabase/storage-js@2078

@supabase/supabase-js

npm i https://pkg.pr.new/@supabase/supabase-js@2078

commit: 37b032d

@coveralls

coveralls commented Jan 29, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 82.801% (-0.1%) from 82.928%
when pulling 37b032d on fix/postgrest-url-validation
into 0cc314a on master.

@mandarini
mandarini force-pushed the fix/postgrest-url-validation branch from 8adab00 to 61abc1a Compare January 29, 2026 15:12
@mandarini
mandarini marked this pull request as ready for review January 29, 2026 15:13
@mandarini
mandarini requested review from a team as code owners January 29, 2026 15:13
@mandarini
mandarini force-pushed the fix/postgrest-url-validation branch from 61abc1a to 04f162a Compare January 29, 2026 15:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/core/postgrest-js/src/PostgrestBuilder.ts (1)

229-283: Avoid empty-string hint/code for generic fetch errors.

When errors aren’t Abort/HeadersOverflow, hint/code become empty strings, which is a behavior change vs. “not present” and can trip strict checks. Consider keeping them null unless explicitly set.

💡 Suggested change
-        let hint = ''
-        let code = ''
+        let hint: string | null = null
+        let code: string | null = null
...
-            hint: hint,
-            code: code,
+            hint,
+            code,
🤖 Fix all issues with AI agents
In `@packages/core/postgrest-js/src/PostgrestClient.ts`:
- Around line 84-109: The abort-signal listener added in PostgrestClient (inside
the this.fetch wrapper where AbortController, originalFetch and existingSignal
are used) can leak if the same AbortSignal is reused; update the code to (1)
register the listener with the options { once: true } and capture the listener
function reference, and (2) ensure you remove that listener in the finally block
that clears timeoutId (so the listener is explicitly removed if the fetch
completes before the signal fires). Locate the existing addEventListener call on
existingSignal and modify it to use a named handler plus { once: true } and
removeEventListener(handler) in the finally that wraps the originalFetch call.

In `@packages/core/postgrest-js/test/timeout-and-url-length.test.ts`:
- Around line 124-145: The test fails because the AbortController's signal isn't
passed into the query and the mock fetch ignores the init.signal; update the
test so the query uses the controller's signal via the query builder's
abortSignal(...) (call .abortSignal(controller.signal) on
postgrest.from('users').select()), and change the fastFetch mock (the local
fastFetch function used by PostgrestClient) to inspect init?.signal and
immediately return a rejected promise with an aborted DOMException (or a
rejected Error with name 'AbortError') if init.signal?.aborted or attach an
'abort' listener to reject when signaled, so the request actually aborts and the
expected error is produced.

In `@packages/core/postgrest-js/tsconfig.json`:
- Around line 12-13: The tsconfig.json is inconsistent: "lib" is ES2022 while
"target" remains ES2017; update the "target" compiler option value to "ES2022"
so it matches the "lib" setting and the repo's TypeScript config convention,
ensuring the compiler emits code compatible with ES2022 features referenced by
the lib.

@steve-chavez

steve-chavez commented Jan 29, 2026 •

Copy link
Copy Markdown
Member

URL Length Warning (PostgrestQueryBuilder.ts)
Console warning when select parameter exceeds 8000 characters

Could we instead have the above protection for the whole URL? Because this can also happen when filters are too large:

@steve-chavez

Copy link
Copy Markdown
Member

And when filters are too large, we can give a hint to solve the error by using RPC to send the values.

@steve-chavez

Copy link
Copy Markdown
Member
  1. Enhanced Error Messages (PostgrestBuilder.ts)
    AbortError responses now include helpful hints
    Links timeout to potential root cause when URL is very long
    Adds PGRST_TIMEOUT error code for easier error handling

Could we leave code empty or perhaps have another prefix? The problem is that postgREST uses the PGRST prefix for its own errors (ref) so PGRST_TIMEOUT could be confused to be a backend error.

I think leaving it empty should be fine as it's a pure client-side error.

@mandarini
mandarini force-pushed the fix/postgrest-url-validation branch 2 times, most recently from a18d394 to a65493f Compare January 30, 2026 09:23
@mandarini
mandarini force-pushed the fix/postgrest-url-validation branch from a65493f to 37b032d Compare January 30, 2026 09:24
@mandarini
mandarini merged commit 7ec2df9 into master Jan 30, 2026
21 checks passed
@mandarini
mandarini deleted the fix/postgrest-url-validation branch January 30, 2026 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

postgrest-js Related to the postgrest-js library.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants