Invalid API key (PGRST301) error when testing Supabase REST API without production credentials
0 reputation · 28 Dec 2021, 18:09 UTC
0 reputation · 28 Dec 2021, 18:09 UTC
The goal is to decide how the supabase‑js client should behave when a request fails with a 401 PGRST301 response caused by an expired or missing anon key during local or CI testing.
Constraints include avoiding accidental exposure of the service_role key, relying only on the anon key supplied by supabase start, and determining whether automatic session refresh should be built into the library or left to the developer.
Should the client automatically call supabase.auth.refreshSession() and retry the original request on a 401 PGRST301 error? If so, should this retry be limited to anon‑key usage and made configurable via client initialization options?
35270 reputation · 29 Dec 2021, 03:00 UTC
A 401 response with code PGRST301 means PostgREST rejected the API key itself. The client should surface this as a configuration error. Automatically calling auth.refreshSession() and replaying the request is the wrong default behavior.
Likely explanation: PostgREST validates the apikey header before any Supabase Auth session logic runs. When the anon key is missing, malformed, or expired, the gateway returns PGRST301 immediately. auth.refreshSession() exchanges a refresh token for a new user access token; it does not mint or rotate the project anon key. Replaying the request with the same rejected apikey header will fail again.
Confirmed behavior: The anon key is sent as apikey and usually as the Authorization: Bearer token for anonymous REST access. User-session refresh changes the user JWT, not the configured project credential. Unless the application itself replaces the apikey header, a retry cannot repair an expired or rotated key from supabase start.
PGRST301 propagate to the caller with its status code and message. Do not silently retry.PGRST301 as a pipeline configuration failure. Verify that the anon key from supabase start is passed correctly to the client environment.service_role key.Before deciding whether any refresh logic is relevant, inspect the failing request headers. Do apikey and Authorization carry the anon key, or do they carry a user access token? If they carry the anon key, session refresh is irrelevant. If they carry a user access token, the problem may be session expiry rather than an invalid project key, and the handling changes accordingly.
Local key lifetime, rotation behavior, PostgREST error mapping, and supabase-js interceptor behavior can change across versions. Verify the exact 401 body and headers against your installed CLI and client version before relying on any retry or error-code mapping.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.