Authentication serves as a protective barrier for software applications, verifying the identity of users and granting access to protected resources. However, requiring users to authenticate multiple times, especially within a single session, can lead to frustration, hinder productivity, and ruin their overall experience.
To address this challenge, you can employ cookies and session storage to store user credentials and other personalized information. This allows users to remain authenticated throughout their session without having to constantly re-authenticate, ultimately improving the user experience.
Managing user session data using cookies and session storage
Managing user sessions is a key aspect of building strong and secure React apps. Properly managing session data through cookies and session storage ensures a velvety and personalized user experience while maintaining necessary security measures.
User session data typically includes information specific to the user’s current session or interaction with an application. This data may vary depending on the application’s requirements and functionality, but typically includes the following:
- Authentication information.
- User preferences and settings.
- User activity and history.
Cookies are text files containing miniature pieces of data stored by web browsers on a user’s device. They are commonly used to store login credentials and any other personalized user information, allowing web applications to maintain a user’s session across multiple browser sessions.
On the other hand, session storage—similar to local storage—is a client-side storage mechanism provided by state-of-the-art browsers. Unlike cookies, it is confined to a specific browsing session and available only within the same tab or window. Session storage offers a straightforward and straightforward way to store session-specific data for web applications.
Both cookies and session storage play a key role in managing user session data. Cookies are great for situations where you need data to persist across sessions. Session storage, on the other hand, is beneficial when you want to isolate data within a single browsing session, providing a lightweight and specific storage option.
We will now look at how to handle user session data, focusing in particular on storing authentication information using cookies and session storage.
Set up a React project
To get started, set up a React project using Vite. Then install these packages into your project.
npm install js-cookie react-router-dom
Ideally, after a user logs in and their credentials are successfully authenticated by the back-end authentication API, cookies and session storage store authentication tokens, session identifiers, or other relevant data used during the user session.
These tokens or identifiers, along with additional data stored in the user’s browser, are automatically included in subsequent requests sent to the server for verification before the user can access protected resources.
This way, the user session is preserved across multiple requests, ensuring a seamless user interaction with the application without the need to re-authenticate on each request.
Managing User Authentication Session Data Using Cookies
To demonstrate how to employ cookies to store user authentication information, go ahead and create a fresh components/Login.jsx file in source directory. Inside this file add the following code.
- Perform the following imports.
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie'; - Create a functional component and add JSX elements for the login form.
const Login = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');return (
Since we don’t have an API backend to authenticate user credentials, we’ll create a function that validates the user’s input on the login form using the test user credentials. Inside the functional component, add the following code.
const testAuthData = {
username: 'test',
password: 'test',
};
const authenticateUser = (username, password) => {
if (username === testAuthData.username && password === testAuthData.password) {
const userData = {
username,
password,
};
const expirationTime = fresh Date(fresh Date().getTime() + 60000);
Cookies.set('auth', JSON.stringify(userData), { expires: expirationTime });
return true;
}
return false;
};
const handleLogin = (e) => {
e.preventDefault();
const isAuthenticated = authenticateUser(username, password);
if (isAuthenticated) {
navigate('/protected');
} else {
}
};
Inside authenticateUser function checks if the provided username and password match the test credentials. If the credentials match, it creates user data object with username and password. It then sets the expiration time for the cookie and stores user data in a cookie called authorize using Cookie files.set method.
After successful authentication, the user is redirected to a protected page because they have permission to access protected resources. By storing authentication information in a cookie, you establish an lively user session, allowing subsequent requests to automatically include authentication details.
User session data allows the server code to verify the user’s identity and authorize access to privileges without requiring the user to reauthenticate on each request.
Update App.jsx file
Make changes to Application.jsx file to handle user routing after successful authentication
import { BrowserRouter, Route, Routes, useNavigate } from 'react-router-dom';
import Cookies from 'js-cookie';
import Login from './components/Login';const ProtectedPage = ({ ...rest }) => {
const isAuthenticated = !!Cookies.get('auth');
const navigate = useNavigate();
const handleLogout = () => {
Cookies.remove('auth');
navigate('/login');
};
if (!isAuthenticated) {
navigate('/login');
return null;
}
return (