Implementing FaceIO for Facial Recognition in React: A Step-by-Step Guide
Pius oruko
Posted on May 3, 2023
Facial recognition has become an increasingly popular technology in recent years, with numerous applications in security, authentication, and user experience. One of the most powerful tools available for facial recognition is FaceIO by PixLab, a cloud-based API that allows developers to quickly and easily implement facial recognition capabilities in their applications.
In this article, we'll explore how to use FaceIO in a React application to build a simple facial recognition system. We'll start by discussing the basics of FaceIO and how it works, then move on to setting up a React project and integrating FaceIO into it. By the end of this tutorial, you'll have a solid understanding of how to use FaceIO in your own React applications, and be able to build powerful facial recognition systems that can be used in a variety of contexts.
How it works
Faceio is a facial recognition tool that can be integrated into web applications to enable secure user authentication. To use Faceio, developers must first initialize their application with a unique application ID obtained by signing up for the service. Once initialized, the developer can add Enroll and Authenticate buttons to their application and use the provided fio.js library to handle the facial recognition functionality. When a user clicks the Enroll button, the enroll() function is invoked to capture and store the user's facial features. On subsequent Authenticate button attempts, the authenticate() function is used to compare the stored facial features with the user's current appearance. If a match is found, the user is successfully authenticated. To ensure a smooth user experience, the developer must also handle any errors that may occur during the facial recognition process. The error codes and descriptions can be found in the fio.js documentation.
Getting started
npm init vite@latest my-react-app --template react
This command uses the npm init command with the vite package to create a new project named my-react-app. The --template option specifies that we want to use the React template provided by Vite, which will set up a new React project with all the necessary dependencies and configuration files. This is what the project structure will be like when you open the project folder using the code editor you are using.
project-root/
├── node_modules/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── index.js
│ ├── App.js
│ ├── components/
│ ├── pages/
│ ├── assets/
│ ├── utils/
│ └── ...
├── .gitignore
├── package.json
├── README.md
├── tsconfig.json
└── vite.config.js
To begin implementing facial recognition using FaceIO, start by adding their JavaScript library to your index.html file. This can be done by including their content delivery network (CDN) link within the body tag of your HTML document. It's important to note that you should always load the fio.js library directly from cdn.faceio.net, rather than self-hosting it. This ensures that you'll receive bug fixes and new features.
<body>
<script src="https://cdn.faceio.net/fio.js"></script>
<div id="root"></div>
<script type="module" src="/src/App.jsx"></script>
</body>
To obtain FaceIO IDs, you need to sign up for a FaceIO account. Once you have created an account, you can access your FaceIO IDs inside the FaceIO console. The FaceIO console is an online platform where you can manage your FaceIO account, including your API keys and access to the FaceIO AI models. After logging in to the FaceIO console, navigate to the "API Keys" section to view your FaceIO IDs. From there, you can copy and use the IDs in your code to interact with FaceIO's AI models, including its facial recognition features.
Create a new FaceIO application to get a public ID
Next, inside the src/ directory of the project, open the App.jsx file and add the following source code;
// Import required dependencies and CSS
import "./App.css";
import { useState, useEffect } from "react";
// Define the App component
function App() {
// Set up state variables for FaceIO instance and error messages
const [faceio, setFaceio] = useState(null);
const [error, setError] = useState(null);
// Use useEffect hook to initialize FaceIO instance when component mounts
useEffect(() => {
const initializeFaceIO = async () => {
try {
// Create a new instance of FaceIO with your public ID
const faceioInstance = new faceIO("YOUR_PUBLIC_ID");
// Update state with the instance
setFaceio(faceioInstance);
} catch (error) {
// Set error state if initialization fails
setError("Failed to initialize FaceIO: " + error.message);
}
};
initializeFaceIO();
}, []);
// Define function to handle enrollment
const handleEnroll = async () => {
try {
// Call the enroll method of the FaceIO instance with necessary options
const response = await faceio.enroll({
locale: "auto",
payload: {
email: "example@gmail.com",
pin: "12345",
},
});
// Log enrollment details to the console
console.log(Unique Facial ID: ${response.facialId} Enrollment Date: ${response.timestamp} Gender: ${response.details.gender} Age Approximation: ${response.details.age});
} catch (error) {
// Set error state if enrollment fails
setError("Enrollment failed: " + error.message);
}
};
// Define function to handle authentication
const handleAuthenticate = async () => {
try {
// Call the authenticate method of the FaceIO instance with necessary options
const response = await faceio.authenticate({
locale: "auto",
});
// Log authentication details to the console
console.log(Unique Facial ID: ${response.facialId} PayLoad: ${response.payload});
} catch (error) {
// Set error state if authentication fails
setError("Authentication failed: " + error.message);
}
};
// Render the component
return (
<section>
<h1>Facial Authentication with FaceIO</h1>
<button onClick={handleEnroll}>Enroll</button>
<button onClick={handleAuthenticate}>Authenticate</button>
{error && <div className="error">{error}</div>}
</section>
);
}
// Export the App component as default
export default App;
The component above, imports useState and useEffect hooks from the react package, as well as the App.css file. It defines a App function component that returns a section containing a title, two buttons, and an error message.
The useState hook is used to declare two state variables, faceio and error, which are initialized as null. The faceio variable will hold the instance of the faceIO class provided by the FaceIO API, while error will hold any error messages that might occur during the authentication process.
The useEffect hook is used to initialize the faceio variable with a new instance of the faceIO class using the FaceIO public ID. If an error occurs during initialization, it will be caught and displayed in the error variable.
Two asynchronous functions, handleEnroll and handleAuthenticate, are defined to handle the enrollment and authentication processes, respectively. They both make use of the await keyword to wait for the response from the FaceIO API.
handleEnroll sends an enrollment request to the FaceIO API with the user's email and pin as payload. If the request is successful, it logs the user's facial ID, enrollment date, gender, and age approximation to the console. If an error occurs, it sets the error variable with an appropriate message.
handleAuthenticate sends an authentication request to the FaceIO API. If the request is successful, it logs the user's facial ID and payload to the console. If an error occurs, it sets the error variable with an appropriate message.
The component returns a section containing a title, two buttons, and an error message. Clicking on the "Enroll" button calls the handleEnroll function, while clicking on the "Authenticate" button calls the handleAuthenticate function. If an error occurs during the authentication process, the error message will be displayed on the page. This is how the final version of the FaceIO integration project will look:
Privacy and security at Faceio
Facial ID is a unique identifier assigned anonymously by the facial recognition engine to each enrolled user on the FACEIO application, facilitating GDPR compliance and privacy protection. The facial recognition engine maps each enrolled user's face into a mathematical feature vector, which is stored as a biometric hash in a sand-boxed binary index. The two production-hardened facial recognition engines available are PixLab Insight and AWS Rekognition. Facial vectors are meaningless on their own and cannot be reverse-engineered. Facial ID deletion occurs via a simple REST API call to the /DELETEFACIALID API endpoint. Facial IDs are subject to data protection, including the right to be forgotten. Privacy and security are addressed with TLS encrypted transactions, security configuration options, and PIN code requirements, among others.
Thanks for taking the time to read this tutorial guide.
Posted on May 3, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.