J José Leiva

Improving User Experience: Managing Session Expiration in React

The Problem with Silent Logouts

There is nothing more frustrating for a user than filling out a complex form or reviewing data, only to have their session quietly expire. In our work on the Proyecto-FinanzApp.io project, we noticed that unauthorized API calls were leaving the UI in an inconsistent state, leading to broken modals and confused users.

To improve the reliability of our application, we decided to implement a proactive session management system that detects JWT expiration and alerts the user before their work is lost.

The Implementation Strategy

We utilized an Axios interceptor to act as a global watchdog for our HTTP requests. By monitoring the response headers and status codes, we can identify when a token is no longer valid.

Intercepting Unauthorized Access

Instead of letting the application fail silently, our interceptor now detects 401 Unauthorized responses and triggers a UI notification:

import axios from 'axios';

const apiClient = axios.create({
  baseURL: 'https://example.com/api'
});

apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // Notify the user via a global state or modal
      triggerSessionExpiredModal();
    }
    return Promise.reject(error);
  }
);

Refined UI Components

Beyond session handling, we focused on fixing issues with our editing modals. By applying consistent CSS transitions and ensuring that state is correctly cleared when a modal is closed, we provided a more polished and responsive experience.

Key Takeaways

  1. Proactive Feedback: Always anticipate session timeouts in your UI to prevent data loss.
  2. Centralized Error Handling: Use Axios interceptors to centralize your auth logic rather than repeating it across every component.
  3. State Hygiene: Ensure that modal components reset their internal state upon closing to avoid residual data bugs when reopened.

By unifying these two improvements, the application now feels significantly more robust, handling authentication lapses gracefully while maintaining a clean user interface.


Generated with Gitvlg.com

Improving User Experience: Managing Session Expiration in React
J

José Leiva Campos

Author

Share: