Skip to content

[Bug]: OAuth login with Discord fails in production with state_security_mismatch and State not found #80

@BENZOOgataga

Description

@BENZOOgataga

Summary

OAuth login with Discord fails in production with state_security_mismatch and State not found, despite correct redirect URI configuration.

This may be related to better-auth/better-auth#4998.


Problem statement

In production (HTTPS, reverse proxy, multi-subdomain setup), the Discord OAuth flow starts correctly but fails on callback with:

ERROR [Better Auth]: State not found
State mismatch: State not persisted correctly (state_security_mismatch)

Infrastructure:

Environment variables:

APP_URL=https://corpsim.altitude-interactive.com
WEB_URL=https://corpsim.altitude-interactive.com
NEXT_PUBLIC_APP_URL=https://corpsim.altitude-interactive.com

API_URL=https://corpsim-api.altitude-interactive.com
NEXT_PUBLIC_API_URL=https://corpsim-api.altitude-interactive.com

CORS_ORIGIN=https://corpsim.altitude-interactive.com

Discord redirect URI configured as:

https://corpsim.altitude-interactive.com/api/auth/callback/discord

The redirect URI is correctly registered in the Discord Developer Portal.

Flow description:

  1. User clicks "Login with Discord"
  2. Redirect to Discord succeeds
  3. After authorization, callback hits /api/auth/callback/discord
  4. Backend throws state_security_mismatch

This suggests the OAuth state is not being persisted or not being read correctly on callback.


Proposed investigation

Potential causes to investigate:

  • OAuth state cookie not persisted correctly behind reverse proxy
  • Incorrect host or protocol detection without proper trust proxy configuration
  • Cookie domain mismatch between corpsim.altitude-interactive.com and corpsim-api.altitude-interactive.com
  • Secure or SameSite attributes preventing cookie from being sent on callback

Relevant details:

  • Reverse proxy forwards X-Forwarded-Proto
  • Multi-subdomain setup
  • HTTPS in production

Given the similarities, this may align with the behavior described in issue #4998.


Additional context

The issue does not reproduce in local development (http://localhost).

Only production (HTTPS + proxy + subdomains) triggers the state mismatch.

Any guidance on recommended cookie configuration or proxy-related setup for Better Auth in this scenario would be ap

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions