A Demo of Face Recognition Authentication in Next.js

How to perform face recognition authentication using Next.js

ā€¢

Thumbnail Hello, developers!Ā šŸ‘‹ Welcome to another of my blog posts.

Face Recognition AuthenticationĀ is the future of login and identity verification. In a world filled with passwords that are easily forgotten or stolen, facial biometrics provide a convenient and secure way for users to verify who they are.

In this blog post,Ā I'll be showing aĀ demo Next.js applicationĀ which implements face authentication using theĀ FACEIO APIĀ in a Next.js project.

TheĀ goal of the demoĀ is to show developers how they can addĀ Face Recognition AuthenticationĀ to their own React/Next.js or any other apps.

Let's Start with a DEMO šŸ‘‡.


Click here for Demo šŸŸ¢

Source Code šŸ‘†

The faceioAuth demo usesĀ Faceio ApiĀ andĀ @faceio/fiojsĀ for Facial Authentication .

It allows users to enroll their face for authentication by capturing images during an enrollment process. Once enrolled, a user can log in by verifying their face against what was captured during enrollment.

FACEIO Documantation šŸ“

The core technology powering the face recognition isĀ faceio.Ā Faceio is an API and SDKĀ that makes it easy to add facial authentication to websites and apps. Some key capabilities ofĀ FACEIOĀ include:

  • Face detection - Detect and capture faces in real time camera.
  • Face enrollment - Capturing facial features to create a user profile.
  • Face verification - Comparing a new face image to an enrolled profile.
  • Web support - Can Works across different web frameworks .

Implement Faceio in your React/Next.js app šŸ¤”

To Implement Faceio in your react/nextjs app is very simple there is a predefined function inĀ FACEIOĀ likeĀ enroll()Ā &Ā authenticate()Ā :

1. Get your api key and public_id

  • After you compleated all the steps and create your application simply implementĀ fio.jsĀ by runningĀ npm i @faceio/fiojs, its a facial recognition JavaScript library, and initialize the library with your applicationĀ Public ID.
  • if your areĀ facing any problemĀ in integrating checkout their šŸ‘‡.

Integration Guide šŸ“–

2. Initialise your Public_id

const initialiseFaceio = async () => {
  try {
    faceioRef.current = new faceIO("Faceio-Public-id");
    console.log("FaceIO initialized successfully");
  } catch (error) {
    console.log(error);
    handleError(error);
  }
};
useEffect(() => {
  initialiseFaceio();
}, []);

3. Create a Register user function

// HANDLE REGISTER
const handleRegister = async () => {
  try {
    if (!faceioRef.current) {
      console.error("FaceIO instance is not initialized");
      return;
    }

    await faceioRef.current?.enroll({
      userConsent: false,
      locale: "auto",
      payload: { email: `${email}` },
    });
    // here you add you cookie storing logic ...

    toast.success("Successfully Registered user.");
  } catch (error) {
    handleError(error);
    faceioRef.current?.restartSession();
  }
};

4. Create a Login user Function

// HANDLE LOGIN
const handleLogin = async () => {
  try {
    const authenticate = await faceioRef.current?.authenticate();
    console.log("User authenticated successfully:", authenticate);
    setUserLogin(authenticate.payload.email);
    // here you add you cookie storing logic ...
  } catch (error) {
    console.log(error);

    handleError(error);
  }
};

5. Define theĀ handleError()Ā Function


 // HANDLing ERRORs
  function handleError(errCode: any) {
    const fioErrs = faceioRef.current?.fetchAllErrorCodes()!;
    switch (errCode) {
      case fioErrs.PERMISSION_REFUSED:
        toast.info("Access to the Camera stream was denied by the end user");
        break;
      case fioErrs.NO_FACES_DETECTED:
        toast.info(
          "No faces were detected during the enroll or authentication process"
        );
        break;
      case fioErrs.UNRECOGNIZED_FACE:
        toast.info("Unrecognized face on this application's Facial Index");
        break;
      case fioErrs.MANY_FACES:
        toast.info("Two or more faces were detected during the scan process");
        break;
      case fioErrs.FACE_DUPLICATION:
        toast.info(
          "User enrolled previously (facial features already recorded). Cannot enroll again!"
        );
        break;
      case fioErrs.MINORS_NOT_ALLOWED:
        toast.info("Minors are not allowed to enroll on this application!");
        break;
      case fioErrs.PAD_ATTACK:
        toast.info(
          "Presentation (Spoof) Attack (PAD) detected during the scan process"
        );
        break;
      case fioErrs.FACE_MISMATCH:
        toast.info(
          "Calculated Facial Vectors of the user being enrolled do not matches"
        );
        break;
      case fioErrs.WRONG_PIN_CODE:
        toast.info("Wrong PIN code supplied by the user being authenticated");
        break;
      case fioErrs.PROCESSING_ERR:
        toast.info("Server side error");
        break;
      case fioErrs.UNAUTHORIZED:
        toast.info(
          "Your application is not allowed to perform the requested operation (eg. Invalid ID, Blocked, Paused, etc.). Refer to the FACEIO Console for additional information"
        );
        break;
      case fioErrs.TERMS_NOT_ACCEPTED:
        toast.info(
          "Terms & Conditions set out by FACEIO/host application rejected by the end user"
        );
        break;
      case fioErrs.UI_NOT_READY:
        toast.info(
          "The FACEIO Widget could not be (or is being) injected onto the client DOM"
        );
        break;
      case fioErrs.SESSION_EXPIRED:
        toast.info(
          "Client session expired. The first promise was already fulfilled but the host application failed to act accordingly"
        );
        break;
      case fioErrs.TIMEOUT:
        toast.info(
          "Ongoing operation timed out (eg, Camera access permission, ToS accept delay, Face not yet detected, Server Reply, etc.)"
        );
        break;
      case fioErrs.TOO_MANY_REQUESTS:
        toast.info(
          "Widget instantiation requests exceeded for freemium applications. Does not apply for upgraded applications"
        );
        break;
      case fioErrs.EMPTY_ORIGIN:
        toast.info("Origin or Referer HTTP request header is empty or missing");
        break;
      case fioErrs.FORBIDDDEN_ORIGIN:
        toast.info("Domain origin is forbidden from instantiating fio.js");
        break;
      case fioErrs.FORBIDDDEN_COUNTRY:
        toast.info(
          "Country ISO-3166-1 Code is forbidden from instantiating fio.js"
        );
        break;
      case fioErrs.SESSION_IN_PROGRESS:
        toast.info(
          "Another authentication or enrollment session is in progress"
        );
        break;
      case fioErrs.NETWORK_IO:
      default:
        toast.info(
          "Error while establishing network connection with the target FACEIO processing node"
        );
        break;
    }
  }

āš™ If your areĀ facing any problem then check out my faceiodemo github repoĀ šŸ‘‰Ā https://github.com/taqui-786/faceioAuthĀ .


Community Contribuition TutorialsšŸ™Œ

More about implementing FACIO in your web application using your favorite JavaScript framework whether it is React, Vue, Angular, Next, React or Vanilla JavaScript.

Checkout More Tutorials ā­


That's it šŸ™

Comment your thoughts on thisĀ Face Recognition AuthenticationĀ and my demo app built with Next.js andĀ FaceIO.

Thanks for reading till here!

Happy Coding šŸ‘‹

Continue Learning

Discover more articles on similar topics