Skip to content

feat(supabase): add canonical CORS headers export for edge functions - #2071

Merged
mandarini merged 3 commits into
masterfrom
feat/cors-module
Feb 5, 2026
Merged

mandarini merged 3 commits into
masterfrom
feat/cors-module

Conversation

@mandarini

@mandarini mandarini commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor

Tests: Change how integration tests are ran

  • Drop verdaccio and complicated setup
  • Use pkg.pr.new for integration tests

Feature: helper to return CORS headers

Exports canonical CORS configuration from @supabase/supabase-js/cors to prevent CORS errors in Edge Functions when new headers are added to the SDK.

What's New

  • corsHeaders - Default CORS config with all Supabase headers
  • Full TypeScript support with comprehensive tests

Problem Solved

Previously, Edge Functions used hardcoded CORS headers from docs. When supabase-js v2.93.0 added new headers, all Edge Functions broke with CORS errors, requiring an emergency revert to v2.93.2.

Solution

Edge Functions now import CORS headers directly from the SDK, ensuring automatic synchronization. When new headers are added, Edge Functions get them automatically on SDK update.

Before:

  const corsHeaders = {                                                            
    'Access-Control-Allow-Origin': '*',                                            
    'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey,         
  content-type',                                                                   
  }                                                                                

After:

  import { corsHeaders } from '@supabase/supabase-js/cors'                         

Migration Strategy

  • Non-breaking: Existing hardcoded headers continue to work
  • Conservative: No new headers will be added in v2.x releases
  • Future-proof: Required for v3.0 compatibility

Summary by CodeRabbit

  • New Features

    • Public CORS utilities and dedicated CORS export; new Edge Function endpoints; setup/cleanup scripts for a shared local Supabase test instance.
  • Tests

    • Expanded CORS test coverage (unit, type, Deno, ESM/CJS, integration), new test targets/scripts, and module-resolution checks.
  • Documentation

    • Testing guide reworked to a single-instance local setup/teardown workflow with Edge Function examples.
  • Chores / CI

    • CI streamlined with a reusable integration-tests workflow; removed local-registry plumbing; added script to update preview package URLs; trimmed many CI jobs.

@coderabbitai

coderabbitai Bot commented Jan 28, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds a canonical CORS module and export, new Deno edge functions and comprehensive CORS tests, local Supabase setup/cleanup scripts, switches preview CI to use pkg.pr.new preview artifacts via a reusable integration-tests workflow, and removes Verdaccio/local-registry plumbing.

Changes

Cohort / File(s) Summary
CORS Core & Exports
packages/core/supabase-js/src/cors.ts, packages/core/supabase-js/jsr.json, packages/core/supabase-js/package.json, packages/core/supabase-js/tsdown.config.ts
Add cors module and CorsHeaders/corsHeaders exports; expose "./cors" in package exports; include src/cors.ts in build entries and update tests/type checks.
Edge Functions & Config
packages/core/supabase-js/supabase/functions/cors-validation/index.ts, .../cors-http-methods/index.ts, .../cors-errors/index.ts, packages/core/supabase-js/supabase/config.toml, packages/core/supabase-js/supabase/deno.json
Add three Deno edge functions for CORS scenarios, enable them in config.toml, and add Deno import mappings for package resolution.
Deno Tests & Harness
packages/core/supabase-js/test/deno/*.test.ts, packages/core/supabase-js/test/deno/deno.json, packages/core/supabase-js/test/deno/package.json, packages/core/supabase-js/test/deno/run-deno-test.js
Add multiple Deno integration tests covering CORS, add import-map (deno.json), new test scripts, and pass --import-map=deno.json to the Deno runner.
Unit / Type / Module-resolution Tests
packages/core/supabase-js/test/unit/cors.test.ts, packages/core/supabase-js/test/types/cors.test-d.ts, packages/core/supabase-js/test/module-resolution-cors.test.*
Add unit, tsd type-tests, and ESM/CJS module-resolution tests validating cors exports, types, and runtime header behavior.
Local Supabase orchestration & docs
packages/core/supabase-js/scripts/setup-supabase.sh, packages/core/supabase-js/scripts/cleanup-supabase.sh, packages/core/supabase-js/TESTING.md
Add setup/cleanup scripts to start/stop a shared local Supabase stack (serve functions, export keys, readiness checks) and update TESTING.md to document the single-instance workflow.
CI / Preview / Integration workflows
.github/workflows/ci-supabase-js.yml, .github/workflows/preview-release.yml, .github/workflows/integration-tests.yml
Simplify ci-supabase-js by removing multiple integration jobs; preview-release now produces commit_hash and invokes a new reusable integration-tests workflow that runs tests against preview artifacts.
Registry/tooling removal & pkg.pr.new adoption
.verdaccio/config.yml, scripts/populate-verdaccio.mjs, packages/core/supabase-js/test/deno/setup-deps.js, package.json, scripts/update-pkg-pr-urls.sh
Remove Verdaccio config and publish script and the Deno setup-deps; add scripts/update-pkg-pr-urls.sh to substitute {COMMIT_HASH}; adjust devDeps and adopt https://pkg.pr.new/...@{COMMIT_HASH} preview URLs.
Integration test manifests updated
packages/core/supabase-js/test/integration/*/package.json
Point integration test dependencies for @supabase/supabase-js to https://pkg.pr.new/@supabase/supabase-js@{COMMIT_HASH} for preview artifact resolution.
Nx / project targets
packages/core/supabase-js/project.json, project.json
Add several Nx deno/test targets for supabase-js and remove root local-registry/populate-local-registry targets from root project.json.
Build/tooling tweaks & misc
packages/core/storage-js/tsdown.config.ts, .github/workflows/ci-core.yml, .github/workflows/publish.yml, packages/core/supabase-js/test/deno/.gitignore
Add guarded path checks to tsdown onSuccess renames, minor quoting/formatting fixes in CI workflows, un-ignore deno.json, and small script/manifest edits.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Preview as "preview-release"
    participant Updater as "scripts/update-pkg-pr-urls.sh"
    participant Reusable as "integration-tests (reusable)"
    participant Supabase as "Local Supabase (test:supabase:setup)"
    participant Runners as "Test runners (Deno/Node/Browser/Platforms)"

    Preview->>Preview: compute commit_hash
    Preview->>Updater: run update-pkg-pr-urls.sh(commit_hash)
    Updater-->>Preview: manifests updated (replace {COMMIT_HASH})
    Preview->>Reusable: invoke integration-tests (with commit_hash)
    Reusable->>Supabase: run test:supabase:setup (start services & functions)
    Reusable->>Runners: execute tests against pkg.pr.new artifacts
    Runners-->>Reusable: return results
    Reusable->>Supabase: run test:supabase:stop
    Reusable-->>Preview: publish test outcome
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • grdsdev
  • steve-chavez
🚥 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 clearly summarizes the main change: adding a canonical CORS headers export for edge functions to prevent compatibility issues.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/cors-module

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 supabase-js Related to the supabase-js library. label Jan 28, 2026
@mandarini mandarini self-assigned this Jan 28, 2026
@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@supabase/auth-js

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

@supabase/functions-js

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

@supabase/postgrest-js

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

@supabase/realtime-js

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

@supabase/storage-js

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

@supabase/supabase-js

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

commit: 9649669

@mandarini
mandarini marked this pull request as ready for review January 28, 2026 16:54
@mandarini
mandarini requested review from a team as code owners January 28, 2026 16:54
Comment thread packages/core/supabase-js/src/cors.ts Resolved

@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: 5

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/src/cors.ts`:
- Around line 81-88: The code currently allows origin?: string | string[] and
joins arrays into a comma list (invalid for Access-Control-Allow-Origin); update
createCorsHeaders to accept only a single origin string (or throw/error if an
array is provided) and update the JSDoc for origin to document that callers must
supply a single origin (e.g., by using
validateOrigin(request.headers.get('Origin')) before calling createCorsHeaders).
If you instead want dynamic allowlist behavior, implement logic that reads the
incoming Origin header, validates it against an allowlist (use or add a
validateOrigin function), then echo back only that single origin in
Access-Control-Allow-Origin and add Vary: Origin; do not join arrays into a
comma-separated header value. Ensure references to createCorsHeaders,
validateOrigin, and the origin?: string | string[] type are updated accordingly.

In `@packages/core/supabase-js/supabase/functions/cors-http-methods/index.ts`:
- Around line 6-48: The handler currently returns a body for 204/OPTIONS and for
HEAD requests which breaks HTTP semantics; change the OPTIONS branch (where new
Response('ok', { status: 204, headers: corsHeaders })) to return a null/empty
body (e.g., new Response(null, ...)) and ensure the final response logic that
builds JSON (the Response(JSON.stringify(responseData), ...)) returns an
empty/null body when req.method === 'HEAD' (keep headers intact) so HEAD and 204
responses have no body while other methods continue returning the JSON payload.

In `@packages/core/supabase-js/test/deno/cors-http-methods.test.ts`:
- Around line 11-21: The test's POST isn't CORS-simple because it uses
'application/json'; update the fetch in the simpleMethods loop (variable
simpleMethods and the fetch call using functionUrl) to use a simple content
type—e.g., set headers['Content-Type'] = 'text/plain' and send a plain string
body for POST (or remove the Content-Type/header and body entirely) so the POST
is CORS-simple and the test matches real CORS semantics.

In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 1-2: Remove the unused import "node:buffer" at the top of the test
file: delete the line import 'node:buffer' since the file only uses Deno.test,
fetch and std assertions (assertEquals, assertExists) and that import is not
referenced anywhere.

In `@packages/core/supabase-js/test/module-resolution-cors.test.mjs`:
- Around line 49-53: The test currently uses includes() on the comma-separated
string corsHeaders['Access-Control-Allow-Headers'] (allowedHeaders), which can
yield false positives by matching substrings; change the check to split
allowedHeaders on commas, trim each token and normalize case (e.g., toLowerCase)
into an array, then for each header in requiredHeaders compare exact tokens
(also normalized) and throw the Error if a required header is not present;
update the loop that iterates requiredHeaders to use this tokenized list for
exact matching.
🧹 Nitpick comments (3)
packages/core/supabase-js/test/deno/package.json (1)

7-10: Avoid repeating setup-deps in test:cors-all.
Right now test:cors-all runs setup-deps three times via the sub-scripts. Consider running it once and then invoking the tests directly.

♻️ Suggested adjustment
-    "test:cors-all": "npm run test:cors-validation && npm run test:cors-http-methods && npm run test:cors-errors",
+    "test:cors-all": "npm run setup-deps && node run-deno-test.js cors-validation.test.ts && node run-deno-test.js cors-http-methods.test.ts && node run-deno-test.js cors-errors.test.ts",
packages/core/supabase-js/test/types/cors.test-d.ts (1)

8-8: Unused expectError import.

The expectError function is imported but never used in the test file. Consider removing it or adding test cases that verify type errors are correctly raised (e.g., passing invalid option types to createCorsHeaders).

♻️ Suggested fix
-import { expectType, expectAssignable, expectNotAssignable, expectError } from 'tsd'
+import { expectType, expectAssignable, expectNotAssignable } from 'tsd'

Alternatively, add type error tests:

// Test: createCorsHeaders rejects invalid options
expectError(createCorsHeaders({ origin: 123 }))
expectError(createCorsHeaders({ credentials: 'yes' }))
packages/core/supabase-js/test/deno/cors-validation.test.ts (1)

39-84: Consider extracting header/method validation helpers.

The header and method validation loops are duplicated patterns. Consider extracting a helper function to reduce verbosity:

function assertContainsAll(actual: string, required: string[], label: string) {
  const normalizedActual = actual.toLowerCase()
  for (const item of required) {
    if (!normalizedActual.includes(item.toLowerCase())) {
      throw new Error(`Required ${label} "${item}" not found in: ${actual}`)
    }
  }
}

This is optional as the current code is readable and explicit.

Comment thread packages/core/supabase-js/src/cors.ts Resolved

@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: 1

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 17-28: The test name "OPTIONS preflight - should return 204
status" and the assertion in the t.step callback are inconsistent: update the
assertion that checks the response status to expect 204 (change the
assertEquals(response.status, 200) to assertEquals(response.status, 204)) so the
t.step block that performs the fetch (using functionUrl and the response
variable) matches the test name and the similar preflight check later in the
file.
🧹 Nitpick comments (2)
packages/core/supabase-js/src/cors.ts (1)

157-166: Consider clarifying the dynamic validation example.

The example shows origin: validatedOrigin || '*' as a fallback, but validateOrigin() returns a boolean, not the origin string. The pattern should use the request origin directly after validation:

const requestOrigin = req.headers.get('Origin')
if (!validateOrigin(requestOrigin, allowedOrigins)) {
  return new Response('Forbidden', { status: 403 })
}
const corsHeaders = createCorsHeaders({
  origin: requestOrigin || '*'  // requestOrigin, not validatedOrigin
})

The actual example in validateOrigin's JSDoc (lines 232-256) shows this correctly.

packages/core/supabase-js/test/deno/cors-validation.test.ts (1)

60-65: Use exact token matching for header validation.

The current implementation uses allowedHeadersLower.includes(header.toLowerCase()) which performs substring matching on the comma-separated string. This could cause false positives (e.g., 'accept' matching inside 'accept-profile').

For consistency with the fix applied to module-resolution-cors.test.mjs, use split + trim for exact token matching:

♻️ Suggested fix
-      const allowedHeadersLower = allowedHeaders.toLowerCase()
-      requiredHeaders.forEach((header) => {
-        if (!allowedHeadersLower.includes(header.toLowerCase())) {
-          throw new Error(`Required header "${header}" not found in: ${allowedHeaders}`)
-        }
-      })
+      const allowedHeaderTokens = allowedHeaders.split(',').map((h) => h.trim().toLowerCase())
+      requiredHeaders.forEach((header) => {
+        if (!allowedHeaderTokens.includes(header.toLowerCase())) {
+          throw new Error(`Required header "${header}" not found in: ${allowedHeaders}`)
+        }
+      })

Comment thread packages/core/supabase-js/src/cors.ts Resolved
@mandarini
mandarini force-pushed the feat/cors-module branch 3 times, most recently from f7bb6fb to cadfcb4 Compare January 30, 2026 13:27

@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: 1

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/unit/cors.test.ts`:
- Around line 66-72: The test expects createCorsHeaders to throw when origin is
an array but the implementation lacks this check; update createCorsHeaders to
validate the origin parameter (in packages/core/supabase-js/src/cors.ts) by
detecting if origin is an Array and throwing Error('Access-Control-Allow-Origin
does not support multiple origins'), or alternatively remove/adjust the test to
match current behavior—preferably add the array check inside createCorsHeaders
so functions like createCorsHeaders(...) and any callers consistently reject
array origins with the exact message the test asserts.
🧹 Nitpick comments (2)
packages/core/supabase-js/test/types/cors.test-d.ts (1)

44-45: Type test may mislead about runtime behavior.

This tests that createCorsHeaders({ credentials: true }) compiles, but at runtime this will throw because credentials: true with the default origin: '*' is invalid. While type tests focus on compile-time validity, consider adding a comment clarifying this is a type-only check and the call would throw at runtime.

💡 Suggested clarification
 // Test: createCorsHeaders with credentials
+// Note: This tests type validity only; at runtime, credentials: true without
+// an explicit origin would throw (default origin is '*')
 expectType<CorsHeaders>(createCorsHeaders({ credentials: true }))
packages/core/supabase-js/test/unit/cors.test.ts (1)

16-30: Consider exact token matching for header validation.

Similar to the ESM test fix, using toContain on the comma-separated header string could theoretically produce false positives (e.g., accept matching inside accept-profile). While the current header names don't overlap in practice, consider using exact token matching for consistency with the module resolution tests.

💡 Suggested approach
it('should include all Supabase custom headers', () => {
  const allowedHeaders = corsHeaders['Access-Control-Allow-Headers']
  const headerTokens = allowedHeaders.split(',').map((h) => h.trim().toLowerCase())

  const requiredHeaders = [
    'authorization',
    'x-client-info',
    'apikey',
    'content-type',
    'x-supabase-api-version',
    'accept-profile',
    'content-profile',
    'prefer',
    'accept',
    'x-region',
  ]

  for (const header of requiredHeaders) {
    expect(headerTokens).toContain(header)
  }
})

@mandarini
mandarini requested a review from a team as a code owner January 30, 2026 13:38

@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: 1

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/package.json`:
- Around line 68-71: The package supabase-js's package.json is missing tsd in
devDependencies while the "test:types" npm script invokes tsd; add "tsd"
(matching the workspace version or a compatible semver) to the devDependencies
section of packages/core/supabase-js/package.json so the "test:types" script can
run reliably in all environments, ensuring the script name "test:types" and the
devDependencies entry for "tsd" are present and versioned appropriately.

Comment thread packages/core/supabase-js/package.json Resolved
@mandarini
mandarini force-pushed the feat/cors-module branch 6 times, most recently from ae3a7c1 to 5306823 Compare January 30, 2026 16:24

@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: 2

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/src/cors.ts`:
- Around line 151-156: Remove the two module-level console.log statements in
cors.ts that reference corsHeaders['Access-Control-Allow-Origin'] and the
timestamp (they run on import and pollute consumer output); either delete those
console.log calls entirely or replace them with a gated debug logger (e.g., only
emit when a DEBUG env/flag is set or via an exported logger) so normal imports
do not print to stdout. Ensure references to corsHeaders remain untouched except
for removing the debug prints.

In `@packages/core/supabase-js/test/module-resolution-cors.test.cjs`:
- Around line 49-54: The test currently uses includes() on the raw string
corsHeaders['Access-Control-Allow-Headers'] (bound to allowedHeaders), which can
yield false positives; instead parse allowedHeaders into an array by splitting
on commas, trim each entry and normalize case, then check each requiredHeaders
entry against the array using exact equality (e.g., create a Set of
trimmed/lowercased allowed header names and verify every header from
requiredHeaders is present in that Set) so comparisons are exact rather than
substring-based.

Comment thread packages/core/supabase-js/src/cors.ts Resolved

@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

🤖 Fix all issues with AI agents
In @.github/workflows/ci-supabase-js.yml:
- Around line 210-228: The workflow uses backgrounded test commands (npx nx
test:deno:all, npx nx test:integration, npx nx test:integration:browser, and the
second group npx nx test:next, npx nx test:expo, npx nx test:bun) and then calls
wait without tracking PIDs which can swallow failures; update the script to
capture each background job's PID (use $! after each npx command), store them
(e.g., in an array or distinct variables), then call wait on each PID and check
each wait's exit status, exiting the step with a non-zero code if any waited PID
fails so that any failing test causes the job to fail; apply this
PID-capture-and-check pattern for both the core integration group
(functions/commands: npx nx test:deno:all, npx nx test:integration, npx nx
test:integration:browser) and the platform-specific group (npx nx test:next, npx
nx test:expo, npx nx test:bun).

In `@packages/core/supabase-js/scripts/cleanup-supabase.sh`:
- Around line 8-16: The cleanup block that stops functions currently removes
/tmp/supabase-functions.pid but leaves /tmp/supabase-functions.log behind;
update the logic in the same block that handles FUNCTIONS_PID (the PID-file
check/kill/remove sequence) to also remove the corresponding log file
(/tmp/supabase-functions.log) after the PID file is deleted, ensuring you check
for the log file's existence before attempting to delete it so there are no
errors when the log is already absent.

In `@packages/core/supabase-js/scripts/setup-supabase.sh`:
- Around line 29-34: The script currently exports SUPABASE_ANON_KEY and
SUPABASE_SERVICE_ROLE_KEY via shell export which won’t persist across GitHub
Actions steps; instead run the status commands into temporary variables,
validate they are non-empty and not "null" (fail early if they are), and then
persist them to GITHUB_ENV by appending lines like SUPABASE_ANON_KEY=... and
SUPABASE_SERVICE_ROLE_KEY=... to the file referenced by $GITHUB_ENV; locate the
assignments to SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY in the script and
replace the direct export with a two-step assign-and-validate plus echo >>
$GITHUB_ENV approach so downstream steps see the values.
🧹 Nitpick comments (1)
packages/core/supabase-js/scripts/setup-supabase.sh (1)

9-15: Add a process health check after starting background functions.

The supabase functions serve process may exit immediately (port already in use, missing dependencies, etc.), but the script continues running and only fails later during the curl test at line 38 with an unclear error. Add a check using kill -0 right after the sleep to verify the process is still running and exit with a clear diagnostic message if not.

🔍 Suggested safeguard
 npx supabase functions serve > /tmp/supabase-functions.log 2>&1 &
 FUNCTIONS_PID=$!
 echo $FUNCTIONS_PID > /tmp/supabase-functions.pid
 echo "Functions PID: $FUNCTIONS_PID"
 sleep 3
+if ! kill -0 "$FUNCTIONS_PID" 2>/dev/null; then
+  echo "❌ Functions process exited. See /tmp/supabase-functions.log"
+  exit 1
+fi

Comment thread .github/workflows/ci-supabase-js.yml Resolved
@coveralls

coveralls commented Feb 2, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 82.814%. first build
when pulling 9649669 on feat/cors-module
into 7591a34 on master.

@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: 1

🤖 Fix all issues with AI agents
In `@scripts/update-pkg-pr-urls.sh`:
- Around line 31-47: The script currently only warns when no {COMMIT_HASH}
placeholders are found and still exits 0; change it to fail the script (exit
non‑zero) when no placeholders exist or when no replacements were made.
Specifically, before running sed, use grep on "$file" to check for the literal
"{COMMIT_HASH}" (or count matches) and if none are found print an error and exit
1; after running the sed replacement check that grep for "$COMMIT_HASH" returns
at least one match (or compare counts before/after) and if zero, print an error
and exit 1; update the echo lines around the checks to reflect failure instead
of success. Ensure you reference and use the COMMIT_HASH and "$file" variables
and preserve macOS/Linux sed branches.
🧹 Nitpick comments (1)
scripts/update-pkg-pr-urls.sh (1)

1-3: Consider set -euo pipefail for stricter error detection.
It helps catch unset vars and pipeline failures in a file‑mutating script.

Proposed change
-#!/bin/bash
-set -e
+#!/bin/bash
+set -euo pipefail

Comment thread scripts/update-pkg-pr-urls.sh Resolved
@mandarini
mandarini force-pushed the feat/cors-module branch 2 times, most recently from 9646512 to 9218b23 Compare February 3, 2026 13:48

@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: 1

🤖 Fix all issues with AI agents
In @.github/workflows/preview-release.yml:
- Around line 61-70: The step "Get commit hash" writes to $GITHUB_OUTPUT without
quoting which can cause word-splitting (SC2086); update the echo that appends
"sha=$COMMIT_SHA" to quote the variable and the output file by changing the
append command to use quoted expansions (refer to COMMIT_SHA and GITHUB_OUTPUT
in this step) so the line becomes an echo that redirects to "$GITHUB_OUTPUT"
with the value quoted.
🧹 Nitpick comments (1)
.github/workflows/integration-tests.yml (1)

92-109: Quote $GITHUB_WORKSPACE to satisfy shellcheck.

The $GITHUB_WORKSPACE variable should be quoted to prevent potential word splitting. Static analysis (SC2086) flagged these occurrences.

🛠️ Proposed fix
           cd packages/core/supabase-js/test/integration/next
           npm install --legacy-peer-deps
-          cd $GITHUB_WORKSPACE
+          cd "$GITHUB_WORKSPACE"

           cd packages/core/supabase-js/test/integration/expo
           npm install --legacy-peer-deps
-          cd $GITHUB_WORKSPACE
+          cd "$GITHUB_WORKSPACE"

           cd packages/core/supabase-js/test/integration/bun
           bun install
-          cd $GITHUB_WORKSPACE
+          cd "$GITHUB_WORKSPACE"

Comment thread .github/workflows/preview-release.yml Resolved
@mandarini
mandarini requested a review from a team as a code owner February 3, 2026 14:09

@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: 2

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/project.json`:
- Around line 40-79: The Deno test targets that hit a local Supabase instance
(e.g., test:deno:integration and test:deno:edge-functions) must start Supabase
before running; update each target's dependsOn from ["test:deno:setup"] to
["test:supabase:setup", "test:deno:setup"] so the test:supabase:setup task runs
first, and apply the same change to any other Deno targets that perform real
DB/function calls (e.g., add test:supabase:setup to test:deno:cors-validation,
test:deno:cors-http-methods, test:deno:cors-errors if they require the running
instance).
- Around line 33-39: The "test:deno:setup" Nx target currently runs "npm install
&& deno install" which fails because test/deno is not in the workspace and its
local dependencies cannot be resolved; update the target (named
"test:deno:setup" with executor "nx:run-commands") to remove the "npm install"
step so the command is just "deno install" to match how run-deno-test.js runs
Deno and relies on deno.json import maps.

Comment thread packages/core/supabase-js/project.json Resolved
Comment thread packages/core/supabase-js/project.json Resolved

@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: 1

🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 77-90: The CI step that verifies edge functions uses a plain curl
invocation (RESPONSE/HTTP_CODE) which can hang; update the "Verify edge
functions" block to use curl timeouts (e.g., --connect-timeout and --max-time)
and wrap the POST probe in a bounded retry loop that attempts the curl up to N
times with a short sleep between tries, breaking on 200 and failing after max
attempts; ensure you still populate RESPONSE/HTTP_CODE, print the final status
and dump /tmp/supabase-functions.log on failure so diagnostics remain available.
🧹 Nitpick comments (2)
.github/workflows/integration-tests.yml (1)

5-15: Add least‑privilege workflow permissions.

Default GITHUB_TOKEN permissions are broader than needed here. Restricting to contents: read reduces blast radius without affecting this workflow.

🔒 Proposed change
 on:
   workflow_call:
     inputs:
       commit_hash:
         description: 'Git commit hash for pkg.pr.new URLs'
         required: true
         type: string
+
+permissions:
+  contents: read
packages/core/supabase-js/project.json (1)

40-79: Consider adding inputs to Deno test targets for Nx affected/caching consistency.

♻️ Suggested update (apply to each Deno test target)
     "test:deno:integration": {
       "executor": "nx:run-commands",
+      "inputs": ["testing", "^production"],
       "options": {
         "command": "node run-deno-test.js integration.test.ts",
         "cwd": "{projectRoot}/test/deno"
       },
       "dependsOn": ["test:deno:setup"]
     },

Comment thread .github/workflows/integration-tests.yml Resolved

@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: 2

🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 35-36: The workflow step "Update pkg.pr.new URLs with commit hash"
passes the commit hash unquoted to the script; wrap the input in quotes when
invoking ./scripts/update-pkg-pr-urls.sh to ensure shell safety (quote ${{
inputs.commit_hash }}), i.e., change the run invocation so the argument is
passed as a single quoted string to update-pkg-pr-urls.sh to prevent
word-splitting or unexpected characters from breaking the call.
- Around line 96-113: In the "Prepare platform test dependencies" step, the
unquoted variable $GITHUB_WORKSPACE is used in cd commands (e.g., after npm/bun
installs); update those cd commands to quote the variable so the shell receives
it as a single argument (i.e., use "$GITHUB_WORKSPACE") to prevent
word-splitting and satisfy shellcheck SC2086 while keeping the existing install
flow for packages/core/supabase-js/test/integration/next, expo, and bun.

Comment thread .github/workflows/integration-tests.yml Resolved
Comment thread .github/workflows/integration-tests.yml Resolved

@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: 2

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 54-90: The test currently checks headers/methods using substring
matches (allowedHeadersLower.includes and allowedMethodsUpper.includes) which
allows false positives (e.g., "accept" inside "accept-profile"); change
validation to split the header/method strings into exact token sets and check
membership: parse response.headers.get('Access-Control-Allow-Headers') and
'Access-Control-Allow-Methods' by splitting on commas, trimming, normalizing
case, build Sets, then assert every item in requiredHeaders and requiredMethods
is present in those Sets (refer to variables requiredHeaders,
allowedHeadersLower, requiredMethods, allowedMethodsUpper and the OPTIONS
preflight test block).
- Around line 10-15: Update the in-file test-run instructions in the
cors-validation comment block to tell developers to run the test from the repo
root using Nx instead of running `npm run test:cors-validation` from test/deno;
replace the line that says "Run `npm run test:cors-validation` from test/deno"
with guidance to run "nx run <project>:test:cors-validation" (or the appropriate
Nx target for the packages/core/supabase-js project) from the repository root so
the cors-validation tests are executed via Nx.

@mandarini
mandarini force-pushed the feat/cors-module branch 2 times, most recently from 1a5ea55 to 6bf22e0 Compare February 3, 2026 16:00

@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: 1

🤖 Fix all issues with AI agents
In @.github/workflows/integration-tests.yml:
- Around line 62-70: In the "Install browser dependencies" step, quote the
environment variable usage to avoid word-splitting by replacing mkdir -p
$PUPPETEER_CACHE_DIR with mkdir -p "$PUPPETEER_CACHE_DIR" (reference
PUPPETEER_CACHE_DIR and the Install browser dependencies step) so the workflow
is robust to paths containing spaces and satisfies shellcheck SC2086.
🧹 Nitpick comments (1)
packages/core/supabase-js/scripts/setup-supabase.sh (1)

48-57: Consider exiting with error if all retry attempts fail.

The retry loop prints a warning when all 3 attempts fail but still exits successfully. This could mask edge function startup failures, leading to harder-to-diagnose test failures downstream.

♻️ Proposed change to fail on exhausted retries
   if [ "$HTTP_CODE" = "200" ]; then
     echo "   ✅ Edge functions responding"
     break
   elif [ $i -lt 3 ]; then
     echo "   ⏳ Attempt $i/3 failed (status $HTTP_CODE), retrying..."
     sleep 3
   else
-    echo "   ⚠️  Edge functions may still be initializing (status $HTTP_CODE)"
+    echo "   ❌ Edge functions failed to respond after 3 attempts (status $HTTP_CODE)"
+    echo "   Check /tmp/supabase-functions.log for details"
+    exit 1
   fi
 done

Comment thread .github/workflows/integration-tests.yml Resolved

@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: 1

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/supabase/functions/cors-errors/index.ts`:
- Around line 52-57: The catch block that returns a 500 Response currently
accesses error.message (in the catch handling that constructs the Response with
corsHeaders), which assumes the thrown value is an Error; change it to safely
extract the message by checking the caught value (e.g., use instanceof Error or
typeof) and fall back to String(error) or a default message before serializing
to JSON so non-Error throwables won't cause a runtime crash; update the Response
creation in that catch to use the safe message extraction.
🧹 Nitpick comments (5)
packages/core/storage-js/tsdown.config.ts (1)

31-46: LGTM! Robust handling of parallel build race conditions.

The error handling correctly addresses the scenario where parallel builds might rename the file concurrently. The ENOENT check ensures the build doesn't fail if the file was already renamed.

One minor observation: the access() check is technically redundant since rename() would throw ENOENT anyway if the file doesn't exist, but it does make the intent clearer.

Consider using unknown instead of any for the caught error to align with stricter TypeScript practices:

♻️ Optional type safety improvement
-      } catch (err: any) {
+      } catch (err: unknown) {
         // Ignore ENOENT errors (file already renamed by parallel build)
-        if (err?.code !== 'ENOENT') {
+        if (err instanceof Error && (err as NodeJS.ErrnoException).code !== 'ENOENT') {
           throw err
         }
       }
packages/core/supabase-js/test/deno/edge-functions-integration.test.ts (1)

110-117: Nitpick: Redundant assertion inside conditional.

The assertEquals(error, null) on line 112 is tautological since you're already inside the if (!error) branch. Consider removing it.

♻️ Suggested cleanup
         results.forEach(({ data, error }) => {
           if (!error) {
-            assertEquals(error, null)
             assertExists(data)
             assertEquals(typeof data.message, 'string')
             assertEquals(typeof data.timestamp, 'string')
           }
         })
packages/core/supabase-js/supabase/functions/cors-http-methods/index.ts (1)

37-56: Dynamic property assignment may cause TypeScript errors.

The responseData object is implicitly typed at declaration, but receivedBody is added conditionally later. This could cause TypeScript strict mode errors. Consider declaring the property upfront with an optional type.

♻️ Suggested fix
   // Handle all HTTP methods
-  const responseData = {
+  const responseData: {
+    success: boolean
+    method: string
+    methodType: string
+    timestamp: string
+    corsNote: string
+    corsHeaders: string[]
+    receivedBody?: unknown
+  } = {
     success: true,
     method: req.method,
     methodType,
     timestamp,
     corsNote: isSimpleMethod
       ? 'Simple methods work with basic CORS'
       : 'Non-simple methods require Access-Control-Allow-Methods header',
     corsHeaders: Object.keys(corsHeaders),
   }
packages/core/supabase-js/scripts/setup-supabase.sh (1)

34-35: Split declaration and assignment to detect command failures.

The export VAR="$(cmd)" pattern masks the return code of the command substitution. If npx supabase status or jq fails, set -e won't catch it because export always succeeds. This could leave keys empty without any error.

🛠️ Suggested fix
 echo "🔑 Exporting authentication keys..."
-export SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')"
-export SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')"
+SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')"
+SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')"
+export SUPABASE_ANON_KEY SUPABASE_SERVICE_ROLE_KEY
 echo "   Keys exported"
.github/workflows/integration-tests.yml (1)

67-72: Quote $GITHUB_ENV to prevent word splitting.

Static analysis (SC2086) flags the unquoted $GITHUB_ENV on lines 70-71. While unlikely to contain spaces in CI, quoting follows shell best practices.

🛠️ Suggested fix
       - name: Export auth keys
         run: |
           cd packages/core/supabase-js
-          echo SUPABASE_ANON_KEY="$(npx supabase status --output json | jq -r '.ANON_KEY')" >> $GITHUB_ENV
-          echo SUPABASE_SERVICE_ROLE_KEY="$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" >> $GITHUB_ENV
+          echo "SUPABASE_ANON_KEY=$(npx supabase status --output json | jq -r '.ANON_KEY')" >> "$GITHUB_ENV"
+          echo "SUPABASE_SERVICE_ROLE_KEY=$(npx supabase status --output json | jq -r '.SERVICE_ROLE_KEY')" >> "$GITHUB_ENV"
           echo "✅ Keys exported"

Comment thread packages/core/supabase-js/src/cors.ts Resolved

@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: 2

🤖 Fix all issues with AI agents
In `@packages/core/supabase-js/test/deno/cors-validation.test.ts`:
- Around line 54-60: The test comment claiming "All 10 current Supabase headers
must be allowed" is inconsistent with the actual requiredHeaders array; update
the comment or the array to match: either change the comment to state that the
test checks a minimal subset (e.g., "Check required Supabase headers") or add
the remaining Supabase header names to the requiredHeaders array in
cors-validation.test.ts so the assertion truly covers all 10 headers (modify the
requiredHeaders variable to include the missing header strings).
- Around line 112-152: The test currently only makes an OPTIONS call
(preflightResponse) and a POST but never asserts that
Access-Control-Allow-Headers actually permits the new header; update the test to
inspect preflightResponse.headers.get('access-control-allow-headers') (or
equivalent) and assert it includes 'x-supabase-new-feature' (or '*' if the
function intentionally allows all headers), or if the intended policy is
wildcard, change the test comment to state that Access-Control-Allow-Headers: *
is expected; use the existing preflightResponse variable and keep
assertPreflightStatus checks but add an assertion on the allow-headers value to
validate CORS behavior.

grdsdev
grdsdev previously approved these changes Feb 4, 2026
@mandarini
mandarini merged commit c4a8a43 into master Feb 5, 2026
17 checks passed
@mandarini
mandarini deleted the feat/cors-module branch February 5, 2026 11:32
mandarini added a commit to supabase/supabase that referenced this pull request Feb 5, 2026
v2.95.0 of the supabase-js sdk has been released, which contains
supabase/supabase-js#2071

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Updated guides and examples to recommend using CORS headers from the
Supabase JS SDK (v2.95.0+) instead of manually defining headers.
* Examples now show the SDK-based approach and include a clear fallback
path for older SDK versions that require hardcoded headers.
* Added notes that SDK header updates will be reflected automatically in
edge functions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
joshenlim pushed a commit to supabase/supabase that referenced this pull request Feb 6, 2026
v2.95.0 of the supabase-js sdk has been released, which contains
supabase/supabase-js#2071

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Documentation**
* Updated guides and examples to recommend using CORS headers from the
Supabase JS SDK (v2.95.0+) instead of manually defining headers.
* Examples now show the SDK-based approach and include a clear fallback
path for older SDK versions that require hardcoded headers.
* Added notes that SDK header updates will be reflected automatically in
edge functions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

supabase-js Related to the supabase-js library.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants