Flask session not persisting, losing data on page refresh in SPA

EDIT: I’ve realized that the else statement actually isn’t even being called, but on page refresh, it sets the logged_in value to false. The print inside the else statement never prints. How is it setting to false without me doing it?

I have a Single Page React Application being served by Flask, all on the same server. I am using socket.io-client to communicate between the backend and frontend.

After logging in, the frontend loads up the user data just fine. If I refresh the page, I am logged out and sent back in to the login page. Why is the session not persisting?

The Flask session cookie exists in Chrome. The session cookie id matches the session cookie in the browser even after refreshing and being logged out, but the backend returns that the user is not logged in.

It seems like the session cookie is losing its data on refresh.

Here is a snippet of the react code:

const ENDPOINT = "";
const SocketContext = createContext(null);
const socket = io();

export function useIsLoggedIn() {
  const navigate = useNavigate();

  const [response, setResponse] = useState(data);

  useEffect(() => {
    socket.emit('join', setResponse);
  }, []);

  if (response.success) {
    console.log("routing to dashboard...");

  return response;

export function useLogIn() {
  const sendMessage = (channel, message) => {
    socket.emit(channel, message);

  return { sendMessage };

Here is a snippet of the backend python code:

def on_connect(data):
        if 'logged_in' in session and session['logged_in']:
            user_content = content.get_content(user=session['username'])
            error = None
            emit('sign_in', {'content': user_content, 'error': error, 'success': True}, room=session['company'])
            error = 'Invalid login credentials'
            emit('sign_in', {'content': CONTENT, 'error': error, 'success': False})
    except Exception as e:
        # print(e)

@app.route('/', defaults={'path': ''})
def catch_all(path):
    print('path', path)
        print('session logged_in', session['logged_in'])
    except Exception as e:
        print('failed not logged_in', e)
    if 'logged_in' not in session:
        print('set logged_in to False')
        session['logged_in'] = False
        session.permanent = True
    resp = make_response(render_template('index.html'))
    return resp

I have been trying to figure out for weeks why the session is resetting and logging the user out on refresh. Any help is appreciated, thank you.

1 thought on “Flask session not persisting, losing data on page refresh in SPA”

Leave a Comment