Integrating Spotify Authentication in React with Flask: Issue with Logged-in State Visibility

I’m developing a music application that uses a React frontend and a Flask backend with Spotify’s OAuth authentication. It successfully authenticates when I run only my Flask server. However, once I incorporate it with my React application, I encounter issues regarding the session data.

The process should follow these steps:

  1. The frontend checks if the user is logged in.
  2. If not logged in, it redirects to the Spotify authentication page.
  3. After logging in on Spotify, the app should handle the callback and save the authentication token.
  4. The app should then redirect back to the React application, where the user is expected to be authenticated.

Here are the routes for my Flask backend:

@app.route('/auth-status')
def auth_status():
    session_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
    auth_manager = spotipy.oauth2.SpotifyOAuth(
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_CLIENT_SECRET,
        redirect_uri=CALLBACK_URL,
        scope='user-read-playback-state',
        cache_handler=session_handler
    )
    
    if not auth_manager.validate_token(session_handler.get_cached_token()):
        login_url = auth_manager.get_authorize_url()
        return jsonify({"authenticated": False, "login_url": login_url})

    spotify_client = spotipy.Spotify(auth_manager=auth_manager)
    user_profile = spotify_client.me()
    return jsonify({
        "authenticated": True,
        "profile": {
            "name": user_profile["display_name"],
            "user_id": user_profile["id"],
            "spotify_uri": user_profile["uri"],
            "external_url": user_profile["external_urls"]["spotify"]
        }
    })

@app.route('/spotify-redirect')
def spotify_redirect():
    auth_code = request.args.get('code')
    if auth_code:
        session_handler = spotipy.cache_handler.FlaskSessionCacheHandler(session)
        auth_manager = spotipy.oauth2.SpotifyOAuth(
            client_id=SPOTIFY_CLIENT_ID,
            client_secret=SPOTIFY_SECRET,
            redirect_uri=CALLBACK_URL,
            scope='user-read-playback-state',
            cache_handler=session_handler
        )
        auth_manager.get_access_token(auth_code)
        session.modified = True
        return redirect('http://localhost:3000/')
    return 'Missing authorization code', 400

Below is the React component handling this:

function MainComponent() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [loginUrl, setLoginUrl] = useState('');
  
  useEffect(() => {
    const checkAuthUrl = `http://127.0.0.1:5000/auth-status?timestamp=${Date.now()}`;
    axios.get(checkAuthUrl, { withCredentials: true })
      .then(response => { 
        const { authenticated, login_url } = response.data;
        setIsLoggedIn(authenticated);
        if (!authenticated) {
          setLoginUrl(login_url);
        }
      })  
      .catch(error => console.error('Failed request:', error));
  }, []);

  return (
    <BrowserRouter>
      <div className="MainComponent">
        <header className="app-header">
          <Routes>
            <Route path="/login" element={!isLoggedIn ? <LoginPage loginUrl={loginUrl} /> : <Navigate to="/" />} />
            <Route path="/" element={isLoggedIn ? <SearchMusic /> : <Navigate to="/login" />} />    
          </Routes>
        </header>
      </div>
    </BrowserRouter>
  );
}

I’ve verified that when I call the Flask endpoint directly after the callback, it responds with authenticated: True along with user information. However, my React application continues to receive authenticated: false. What might be causing the session persistence issue between the frontend and the backend?

Classic CORS and session problem - I’ve hit this tons of times. Your Flask session isn’t syncing between Spotify’s callback and your React app requests. Here’s what’s happening: Spotify redirects to /spotify-redirect and creates a session cookie, but when React calls /auth-status, it can’t access that same cookie because of cross-origin restrictions. Fix it by setting up Flask-CORS with supports_credentials=True and configure your session with SameSite='None' and Secure=True. Double-check your Flask secret key is set and stays consistent. That timestamp parameter won’t fix session issues - just get the cookies working properly across domains.

your session config’s broken. check if your flask app has SESSION_COOKIE_HTTPONLY = False - without it, javascript can’t touch the session. also need the samesite settings everyone mentioned. try logging what’s in your session right before the redirect in /spotify-redirect to see if the token’s even saving. could be failing silently.

Had the exact same issue recently - it’s definitely a Flask session problem. Your Spotify callback saves the token to the session, but your React app can’t access it because cross-origin requests don’t include cookies by default. You need to fix your Flask session config beyond just CORS. Set SESSION_COOKIE_SAMESITE = 'None' and SESSION_COOKIE_SECURE = True. Also double-check you’ve got a proper SECRET_KEY - sessions won’t work without it. Caught another issue in your code: you’re using SPOTIFY_SECRET in the callback but SPOTIFY_CLIENT_SECRET in auth-status. That mismatch will break authentication. Pick one variable name and stick with it in both routes.

This is a session storage timing issue mixed with browser security restrictions. When Spotify redirects back to your Flask callback, it creates a new browser context that doesn’t sync immediately with your React app’s session state. I’ve hit this exact problem before. You need to ditch Flask’s default session storage and use something more persistent like Redis or a database. Flask’s in-memory sessions don’t play well with OAuth redirects when you’re using frontend frameworks. Also, set up polling in your React component to check auth status every few seconds after the redirect instead of checking just once. The session data needs time to propagate after Spotify’s callback finishes.