DEV Community

Chidera Ani
Chidera Ani

Posted on • Updated on

User re-authentication in your React app.

An approach to authenticating your users after a period of idle time.

Intro…

One of the ways to beef up your app’s security is to re-authenticate users when necessary. In this guide, we’re going to implement a re-authentication feature on a frontend application using react-idle-timer library to detect when a user has been idle after some time. For this guide, the authentication setup will just be localStorage .

**React-idle-timer **is a javascript library used to detect and monitor user activity on your web application. We’ll be using it for this application, run yarn add react-idle-timer to install on your repo.

The App.

Our Nextjs app will have 2 pages namely login.js and index.js . login.js will contain the login view and logic while index.js will contain our “dashboard” screen and the re-auth logic.


In login.js we’ll create a simple login form and a login function that saves a random token to localStorage and redirects to our index.js page.

For this guide, only the form button is truly functional but ensure your form inputs are also functional in your app.

Next up is our index.js page where the re-auth feature is implemented.

We import useIdleTimer hook from react-idle-timer and call it passing in some properties.

const { isIdle } = useIdleTimer({

onIdle,

timeout: 15000

});
Enter fullscreen mode Exit fullscreen mode

We’re passing 2 properties;

  1. onIdle: a function that is called when our user is idle after some time.

  2. timeout: a period (in milliseconds) of inactivity after which our user is declared idle (onIdle is called). We made timeout 15 seconds for this guide, however in a real app timeout can be 15–30 minutes

useIdleTimer accepts other properties like onActive, crossTab, startManually, etc. but for the purpose and simplicity of this guide, we’ll stick to just 2 properties.



Finally, In our index.js file we create a modal that becomes visible when a user has been idle and the user enters their password to re-authenticate themselves. If they close the modal or reload the page logout function is called.

We’ve gone through a simple way to implement re-authentication in your web apps. You should check out the react-idle-timer documentation for more info and use cases.

Happy coding…..

Top comments (0)