debugpythonfastapiMajor
Spotify OAuth: 3 layers of failure on port change
Viewed 0 times
spotify auth failedCORS OPTIONS 400redirect_uri mismatchNEXT_PUBLIC env varport changedocker-compose .env override
Error Messages
Problem
When running the app's Docker web container on a non-default port (e.g. 3003 instead of 3000), Spotify OAuth login fails with "Failed to authenticate". Three separate issues compound: 1) CORS blocks the OPTIONS preflight because the new origin isn't in FastAPI's allow_origins list, 2) The .env file overrides docker-compose defaults for SPOTIFY_REDIRECT_URI causing a redirect_uri mismatch during Spotify token exchange (frontend sends port 3003, backend sends port 3000), 3) Missing database columns (users.youtube_channel_id) cause a 500 error after successful token exchange because alembic migrations were incomplete.
Solution
Fix all three layers: 1) Add the new origin (http://127.0.0.1:3003) to FastAPI CORSMiddleware allow_origins in main.py. 2) Update SPOTIFY_REDIRECT_URI in the .env file (not just docker-compose.yml) since .env values override compose defaults — both frontend and backend must send the exact same redirect_uri to Spotify. 3) Run
alembic revision --autogenerate and alembic upgrade head to create missing columns. Also remember that NEXT_PUBLIC_ env vars are baked at build time in Next.js — the Docker web container must be rebuilt (not just restarted) after changing these values. Finally, Spotify's redirect URI matching is strict: http://localhost:3003 and http://127.0.0.1:3003 are treated as different URIs.Why
Three independent systems must agree on the same port: 1) CORS origin whitelist, 2) Spotify redirect_uri in both frontend auth URL and backend token exchange, 3) Database schema must match the ORM model. The .env file takes precedence over docker-compose.yml defaults, and NEXT_PUBLIC_ vars are compile-time constants in Next.js.
Context
Changing the port for a Docker-based Next.js + FastAPI app with Spotify OAuth
Revisions (0)
No revisions yet.