How to implement keep-alive polling in React frontend?

Viewed 1379

In my situation, we have Shibboleth authentication proxy that sits between the client and the server. Since there may be cases when a user takes a lot of time to fill out a page without causing any HTTP requests to be made, the Shibboleth may end their session possibly causing the user to lose their work.

To implement keep-alive polling I've made a route for that in our backend. However, I have been unable to implement the actual polling in our React frontend. How do I implement making repeated HTTP requests for as long as the app is open in a client browser? The data returned from a keep-alive request is arbitrary and has no use in the frontend, thus this could possibly be done completely outside React.

1 Answers

Here is my implementation in case it is of any use to someone. You want to refactor it a bit but the functionality is there. It uses React's useEffect hook to set/clear an interval timer that makes the keep-alive request to backend with axios. All encapsulated in a React component.

import React, { useEffect } from 'react';
import axios from 'axios';

/** Poll backend's keep-alive route every 5 minutes to maintain Shibboleth session. */
export default () => {
  const url = process.env.NODE_ENV === 'development' ? 'http://localhost:3001/keepalive' : '/keepalive';

  useEffect(() => {
    const interval = setInterval(() => axios.get(url), 5 * 60 * 1000);
    return () => clearInterval(interval);
  });

  return <div />;
};
Related