Login, 401 & redirect errors

Resolve OAuth redirect mismatches, 401 and 403 permission errors, stale session cookies, and CORS blocks when moving from Preview to Live.

Why sign-in works in Preview but breaks on Live

Login working in Preview yet failing on your custom domain almost always traces to three strict security boundaries enforced by browsers and identity providers.

First, Preview and Live keep isolated user directories and sessions. Accounts and admin roles created in Preview never copy automatically into Live — register fresh on Live first.

Second, OAuth providers validate exact origin URLs character for character. Switching from yourapp.exaspark.app to https://yourdomain.com — or mixing apex and www — rejects callbacks until your Live origin matches.

Third, browsers scope cookies and cross-origin fetches by exact hostname and HTTPS. Cookies from one host do not follow to another, and direct browser calls to third-party APIs fail with CORS errors unless routed through your backend.

Symptom-to-fix diagnosis table

Use this table to isolate whether your issue lives in OAuth configuration, session cookies, server role checks, or cross-origin API calls.

SymptomMost likely causeExact fix
OAuth shows `redirect_uri_mismatch`Callback URL on your custom domain is missing or differs from the registered originConfirm canonical domain (yourdomain.com vs www), re-verify custom domain, and align callback URLs
Preview account says "Invalid login" on LivePreview and Live databases keep separate user tablesSign up fresh on Live, then promote your Live admin inside Cloud → Live
Page bounces back to `/login` in an endless loopSession cookie not stored/sent on active domain, or /login route redirects authenticated checks incorrectlyTest in an incognito window, confirm HTTPS is active, and verify cookie domain plus auth-guard logic
API returns `401 Unauthorized` right after loginFrontend fetch omitted session credentials or session cookie expired/mismatchedSend requests to same-origin /api/... routes with credentials: "include" and verify server session middleware
Signed-in user gets `403 Forbidden` on admin pageUser's role in the active environment is still member, not adminOpen Cloud for the active environment (Preview or Live) and update the user's role
Member gets `403 Forbidden` on own recordOwnership check compares wrong field or mismatched ID type (user_id vs owner_id)Inspect the route handler's ownership filter and ensure user_id derives strictly from the server session
Console shows `Blocked by CORS policy`Browser calls an external third-party API directly instead of via your backendMove the third-party API request into a server-side backend endpoint and keep API keys server-side

Fixing OAuth redirect URI mismatches on custom domains

OAuth failures almost always happen right after connecting a custom domain or enabling a www redirect. Identity providers treat http://, https://, yourdomain.com, and www.yourdomain.com as four completely different origins.

If your visitor opens https://www.yourdomain.com, starts Google sign-in, and your callback redirects back to https://yourdomain.com (or vice versa), the OAuth state cookie can also fail to match and abort sign-in with an invalid state error.

text
Exact Origin Consistency Check
------------------------------------------------------------------
BROKEN (mismatched hosts):
  Visitor opens:      https://www.studionorth.co/login
  OAuth callback:     https://studionorth.co/api/auth/callback/google
  Result:             redirect_uri_mismatch OR invalid OAuth state cookie

CLEAN (canonical redirect + exact match):
  Canonical Live URL: https://studionorth.co  (www 301-redirects to apex)
  Authorized Origin:  https://studionorth.co
  Callback URI:       https://studionorth.co/api/auth/callback/google
  Result:             Cookie and OAuth callback share one exact HTTPS origin

Follow these four steps whenever OAuth stops working after attaching a custom domain:

  1. Verify domain SSL and canonical redirect

    Open Publish settings and confirm your custom domain shows verified with active HTTPS, and that www and apex redirect cleanly to one canonical host. See Custom domains & DNS.

  2. Update provider callback settings

    For any custom OAuth credentials you configured (Google Cloud Console, GitHub OAuth App, Apple, or Microsoft), add the exact canonical https:// origin and callback path with zero trailing-slash typos. See Social login setup.

  3. Check magic-link and reset base URLs

    Confirm password-reset and email-verification links generate URLs pointing to your active Live domain rather than a hardcoded Preview hostname.

  4. Test sign-in in a fresh private window

    Open an incognito window on your canonical Live URL and complete one full sign-in, refresh, and sign-out cycle.

Untangling 401 Unauthorized vs 403 Forbidden

Checking the exact HTTP status code in DevTools Network immediately separates missing sessions from missing permissions.

Diagnosing 401 Unauthorized (missing or rejected session)

HTTP 401 means the server received no valid session cookie — either the user is signed out, the session expired, the browser blocked the cookie, or the frontend called a different origin.

  • Check `Set-Cookie` on login: Inspect the login request in DevTools Network for browser warnings on SameSite or Secure attributes.
  • Use relative `/api/...` paths: Calling a hardcoded .exaspark.app URL from a custom domain causes browsers to withhold first-party cookies.
  • Handle expiry cleanly: Redirect expired sessions to /login?next=<path> and clear cached client UI state automatically on 401.

Diagnosing 403 Forbidden (valid session, blocked permission)

HTTP 403 means the server verified who you are and intentionally denied access based on role or record ownership.

  • Environment role drift: Promoting an admin in Cloud → Preview does not promote that account in Cloud → Live.
  • Row ownership mismatch: Confirm member records save user_id strictly from the verified server session rather than an empty string or email. See Row-level data privacy.
  • Role casing: Verify database role values ("admin") match server middleware checks exactly.

Clearing stale cookies, sessions, and redirect loops

Login loops — bouncing endlessly between /dashboard and /login — occur when browser localStorage caches an old user object while the server's HTTP-only session cookie expired or belongs to a prior domain.

Test in an incognito window first. If sign-in works there, clear site cookies in DevTools (Application → Storage → Clear site data), then rely strictly on the server's /api/auth/me session check as the single source of truth.

Fixing CORS errors the right way

When your browser Console prints Access to fetch at 'https://api.vendor.com/...' has been blocked by CORS policy, the browser is enforcing a built-in security shield called Cross-Origin Resource Sharing.

By default, browsers block JavaScript running on https://yourdomain.com from reading responses returned by a different domain unless that remote server explicitly grants permission via Access-Control-Allow-Origin.

Calling external third-party APIs directly from the browser creates two serious defects at once: browsers block the response with CORS errors, and any API key attached to the request leaks publicly in DevTools.

http
# BROKEN: Browser calls external vendor directly (CORS error + exposed key)
Browser (https://yourdomain.com) ---> https://api.thirdparty.com/v1/rates
  X Blocked by CORS policy; Authorization header visible to every visitor

# CORRECT: Browser calls your own same-origin backend route
Browser (https://yourdomain.com) ---> POST https://yourdomain.com/api/shipping-rates
  -> Your ExaSpark backend validates session, attaches server-side secret,
     calls https://api.thirdparty.com/v1/rates server-to-server,
     and returns clean JSON to the browser (zero CORS issue, zero leaked key).

If you genuinely need a separate frontend domain to call your own API with cookies, remember one strict browser rule: you can never combine `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`. You must echo an explicit allowlisted origin and handle OPTIONS preflight requests cleanly. See External APIs & webhooks and Secrets & env vars.

Copyable prompts for fixing auth and CORS bugs

Paste the exact failing route, status code, and browser behavior into a focused repair prompt.

Use this prompt to fix a custom-domain login loop or post-login 401:

Starter prompt · App

After connecting our custom domain, signing in redirects back to /dashboard and immediately bounces to /login in a loop while `/api/auth/me` returns 401. Ensure all frontend fetches use relative same-origin `/api/...` paths with `credentials: "include"`, derive auth callback and magic-link URLs from the active request origin rather than hardcoded Preview URLs, remove stale `localStorage` auth caching, and make the server session cookie the single source of truth.

Use this prompt to eliminate a browser CORS error on an external API integration:

Starter prompt · App

Our checkout page shows a browser CORS error when fetching shipping rates directly from `https://api.shippo.example/rates`. Move that external API call into a new server-side backend endpoint `POST /api/shipping/rates` that verifies the user's request, reads the shipping API key strictly from server-side secrets, validates the destination ZIP code, and returns only the sanitized rate options to the browser.

Next steps

Still have a question?Ask our team and other builders on Discord.

From the blog