DEV Community

Cover image for Building an AI Vacation Planner Chatbot with Facial Authentication using FACEIO & Next.js
Ekemini Samuel
Ekemini Samuel

Posted on • Originally published at blog.stackademic.com

Building an AI Vacation Planner Chatbot with Facial Authentication using FACEIO & Next.js

Sites de viagem (alguns, pelo menos) têm muitos anúncios e, às vezes, poucas avaliações. E se você pudesse criar seu próprio agente de viagens que reconhece você, verifica sua idade e responde perguntas de viagem instantaneamente?

Neste tutorial, você construirá um chatbot de planejamento de férias alimentado por IA, seguro, que autentica usuários via reconhecimento facial usando FACEIO. Você integrará o Groq AI para conversas rápidas com IA e usará Next.js para criar uma interface moderna.

O FACEIO oferece um SDK JavaScript robusto de reconhecimento facial para permitir login sem senha em sites, autenticação biométrica e muito mais.

travel GIF

Pronto? Vamos começar!


Autenticação Facial com FACEIO antes de acessar o aplicativo Vacation AI

O Que Você Vai Aprender

Você aprenderá como integrar o SDK de reconhecimento facial FACEIO em um aplicativo Next.js, conectar e transmitir respostas de chat do Groq AI API, proteger seu aplicativo de IA com detecção de vivacidade e estruturar aplicativos full-stack com autenticação facial.

GitHub repository

Pré-requisitos

Make sure you have:

Certifique-se de ter:

  • Conhecimento básico de React e Next.js.
  • Node.js (v18+) e npm instalados no seu computador.
  • Uma conta FACEIO para obter sua chave de API.
  • Chave de API do Groq em console.groq.com.
  • Um IDE ou editor de código (como VS Code), Chrome ou Safari e uma webcam no seu computador.

What is FACEIO?

FACEIO é uma API de autenticação facial de ponta que permite que sites implementem login facial online usando tecnologia avançada de reconhecimento facial. Com recursos como API de detecção de vivacidade e SDK de detecção de deepfake, o FACEIO garante autenticação segura e resistente a fraudes. É ideal para casos de uso como::

  • Login sem senha para sites.
  • Autenticação facial para sites.
  • Verificação de idade.
  • Rastreamento de presença de funcionários.
  • Reconhecimento facial local.

FACEIO’s JavaScript SDK (@faceio/fiojs) é fácil de integrar, funciona em qualquer site e suporta navegadores modernos com acesso à webcam. Saiba mais na página de introdução do FACEIO.

Criando a Interface para a Página de Cadastro/Login do Vacation AI

Esta é a estrutura do projeto que estamos construindo:

vacation-ai/
├─ app/                 # Next.js app directory
├─ components/          # Shared UI and functional components
├─ hooks/               # Custom React hooks
├─ lib/                 # Utility functions and libraries
├─ public/              # Static assets (images, icons)
├─ styles/              # Global styles
├─ types/               # TypeScript type definitions
├─ config + build files # Tailwind, tsconfig, next.config, etc.

Enter fullscreen mode Exit fullscreen mode

Antes de começar o design da interface para a página de cadastro/login do Vacation AI, vamos configurar um novo projeto Next.js usando o comando create-next-app. Isso nos dará uma base sólida para o aplicativo.

CCriar um Aplicativo Next.js para o Projeto

Abra seu terminal, navegue até a pasta do seu espaço de trabalho e execute o comando abaixo

npx create-next-app@latest vacation-ai
Enter fullscreen mode Exit fullscreen mode

Esse comando cria um diretório vacation-ai com a estrutura padrão do projeto Next.js. Quando solicitado, selecione Sim para todas as opções (exceto a última — mantenha o alias de importação padrão). Isso instalará TypeScript, Tailwind CSS e todas as dependências necessárias para o seu projeto Vacation AI.

nextjs terminal

Agora, navegue até a pasta do seu novo projeto:

cd vacation-ai
Enter fullscreen mode Exit fullscreen mode

Update your tailwind.config.js:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./app/**/*.{js,ts,jsx,tsx}", "./pages/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};
Enter fullscreen mode Exit fullscreen mode

In ./styles/globals.css, add Tailwind’s base styles:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Install the FACEIO library for facial authentication. Read the docs to learn more.

In the vacation-ai directory, run this command to install fio.js

npm i @faceio/fiojs
Enter fullscreen mode Exit fullscreen mode

After installation, open the project in VS Code:

code .
Enter fullscreen mode Exit fullscreen mode

To ensure TypeScript recognizes the FACEIO module, create a type declaration file.
Inside src/app, create a new file named faceio_fiojs.d.ts and add:

declare module "@faceio/fiojs"
Enter fullscreen mode Exit fullscreen mode

module

This step allows you to import and use the SDK throughout the app without TypeScript errors.


Criando Componentes de Interface Reutilizáveis

Com a base pronta, podemos começar a construir os componentes de interface para o painel do Vacation AI.

Inside the src/app directory, create a components folder:

mkdir src/app/components
Enter fullscreen mode Exit fullscreen mode

Now, create a file Sidebar.tsx and define your sidebar component:

// src/app/components/Sidebar.tsx
export default function Sidebar() {
  return (
    <aside className="w-64 h-screen bg-gray-900 text-white p-4">
      <h2 className="text-2xl font-bold mb-6">Vacation AI</h2>
      <nav>
        <ul className="space-y-4">
          <li><a href="/dashboard">Dashboard</a></li>
          <li><a href="/history">Booking History</a></li>
          <li><a href="/settings">Settings</a></li>
        </ul>
      </nav>
    </aside>
  );
}
Enter fullscreen mode Exit fullscreen mode

Este componente Sidebar será usado em todas as páginas autenticadas do painel do Vacation AI.

Página inicial do aplicativo

landing page

Página de chat com IA do aplicativo

AI chat page

Configurando a Autenticação Facial

Now let’s add a “Login with Face” button. This button will:

  • Open the FACEIO camera UI
  • Capture the user’s face
  • Verify their identity
  • (Optionally) gate access based on age

In the app/auth directory, create a page.tsx file, and enter the code below. This is the code that integrates the authentication for the Vacation AI app with FACEIO.

'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Camera,
  CheckCircle,
  AlertCircle,
  ArrowLeft,
  UserPlus,
} from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import faceIO from '@faceio/fiojs';

export default function AuthPage() {
  const [authState, setAuthState] = useState<
    'idle' | 'scanning' | 'success' | 'error'
  >('idle');
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [faceioInstance, setFaceioInstance] = useState<any>(null);
  const router = useRouter();

  // Initialize FACEIO
  useEffect(() => {
    if (typeof window === 'undefined') return;

    try {
      const fio = new faceIO(process.env.NEXT_PUBLIC_FACEIO_PUBLIC_ID);
      setFaceioInstance(fio);
      console.log('FACEIO initialized successfully');
    } catch (error) {
      console.error('Failed to initialize FACEIO:', error);
      setAuthState('error');
      setErrorMessage(
        'Failed to initialize facial recognition. Please refresh the page.'
      );
    }
  }, []);

  const handleError = (errCode: any) => {
    const fioErrs = faceioInstance?.fetchAllErrorCodes() || {};
    switch (errCode) {
      case fioErrs.PERMISSION_REFUSED:
        return 'Please allow camera access to proceed.';
      case fioErrs.NO_FACES_DETECTED:
        return 'No face detected. Please position your face in the frame.';
      case fioErrs.UNRECOGNIZED_FACE:
        return 'Unrecognized face. Please try again or register.';
      case fioErrs.MANY_FACES:
        return 'Multiple faces detected. Ensure only one face is visible.';
      case fioErrs.FACE_DUPLICATION:
        return 'User already enrolled. Please sign in instead.';
      case fioErrs.FORBIDDEN_ORIGIN:
      case fioErrs.EMPTY_ORIGIN:
        return 'Access restricted. Ensure your domain is whitelisted in the FACEIO console.';
      case fioErrs.TIMEOUT:
        return 'Operation timed out. Please try again.';
      default:
        return 'An error occurred. Please try again.';
    }
  };

  // Handle authentication 
  const handleAuthentication = async () => {
    if (!faceioInstance) {
      setAuthState('error');
      setErrorMessage('Facial recognition not initialized.');
      setTimeout(() => setAuthState('idle'), 3000);
      return;
    }

    try {
      await navigator.mediaDevices.getUserMedia({ video: true });
    } catch {
      setAuthState('error');
      setErrorMessage('Camera access denied. Please allow camera access.');
      setTimeout(() => setAuthState('idle'), 3000);
      return;
    }

Enter fullscreen mode Exit fullscreen mode

This uses faceio.authenticate() to recognize registered faces.

You can also use faceio.enroll() to register new users with their facial biometrics.

Next up: we’ll plug in Groq’s LLaMA 3 API to build the AI-powered travel assistant — and connect it all.


Configurando a API do Chatbot Vacation AI com Groq LLaMA 3

Para alimentar nosso chatbot com o LLaMA 3 do Groq e dar a ele uma personalidade única para planejamento de viagens, precisamos criar uma rota de API backend no Next.js.

No seu projeto Next.js, navegue até o diretório app/api/chat e crie um novo arquivo chamado route.ts. Em seguida, cole o seguinte código

import { createOpenAI } from '@ai-sdk/openai';
import { streamText } from 'ai';
import type { NextRequest } from 'next/server';

export const maxDuration = 30;

const groq = createOpenAI({
  baseURL: 'https://api.groq.com/openai/v1',
  apiKey: process.env.GROQ_API_KEY,
});

export async function POST(req: NextRequest) {
  try {
    const { messages } = await req.json();

    const result = streamText({
      model: groq('llama3-8b-8192'),
      messages,
      system: `You are VacaPlan AI, an expert vacation planning assistant. You help users plan amazing trips by:

      1. Understanding their preferences (budget, duration, interests, travel style)
      2. Suggesting destinations that match their criteria
      3. Creating detailed day-by-day itineraries
      4. Recommending accommodations, activities, and restaurants
      5. Providing practical travel tips and budget breakdowns

      Always be enthusiastic, helpful, and provide specific, actionable recommendations. Format your responses clearly with headings, bullet points, and organized sections when providing itineraries.

      When creating itineraries, include:
      - Daily activities with time estimates
      - Approximate costs for each activity
      - Transportation recommendations
      - Restaurant suggestions for meals
      - Cultural tips and local customs
      - Weather considerations
      - Packing suggestions`,
      temperature: 0.7,
      maxTokens: 2000,
    });

    return result.toDataStreamResponse();
  } catch (error) {
    console.error('Chat API Error:', error);
    return new Response('Internal Server Error', { status: 500 });
  }
}
Enter fullscreen mode Exit fullscreen mode

What This Code Does:

  • Imports AI SDKs: It uses the @ai-sdk/openai package to interface with Groq's OpenAI-compatible API.
  • Initializes Groq API: We set up a custom baseURL and authenticate using your GROQ_API_KEY environment variable.
  • Handles POST requests: When the frontend sends a list of messages (user chats), this API:

    • Feeds the messages into the LLaMA 3 model.
    • Sets a "system prompt" that trains the assistant to behave like a vacation planning expert (called VacaPlan AI).
    • Returns a streamed AI response in real-time.

This route enables seamless backend communication for the chatbot. Now, whenever the frontend sends a chat message, the AI chatbot responds as if you hired your own expert travel planner ✈️🌍.


Integrando o FACEIO ao Aplicativo Web Next.js

At this point, we have the AI vacation planner and components. Next, we will integrate FACEIO to authenticate users when they sign up/log in, before accessing the AI chatbot.

Create a FACEIO account and sign in to your FACEIO Console to get the credentials needed to add Facial authentication.

FaceIO Console

On the FACEIO dashboard, click on New Application to create a FACEIO application, and follow the steps in the application wizard.

When asked to select a Facial Recognition Engine for the application, choose PixLab Insight. The engine will be used to map each enrolled user’s face in real-time into a mathematical feature vector, known as a biometric hash, which is stored in a sand-boxed binary index. This is used to protect the data of users when they are authenticated with FACEIO.

facio app

Your new FACEIO app will have an ID number; take note of it as we'll be using it to integrate FACEIO into the web application.

FACEIO appID

Go to the SignupForm.tsx file and declare a variable; faceio that will initialise the FACEIO SDK with your specific FACEIO application ID. The FACEIO app ID will be retrieved from an environment configuration env file.

In the root directory of your Next.js project, create a new file named .env.local and enter this to define the environment variable:

NEXT_PUBLIC_FACE_IO_ID=your_faceio_app_id_here
Enter fullscreen mode Exit fullscreen mode

Replace "your_faceio_app_id_here" with your actual FACEIO application ID, and add .env.local to your .gitignore file

Running the Vacation AI application

Create an .env.local file in your root directory and add these details:


NEXT_PUBLIC_FACEIO_PUBLIC_ID=your-faceio-public-id
GROQ_API_KEY=your-groq-api-key
Enter fullscreen mode Exit fullscreen mode
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

Go to: http://localhost:3000

The landing page shows in your browser like so:

landing page

Click on "Start Planning", it will redirect you to the Facial authentication page with FACEIO.

Facial authentication

Authenticate → Chat → Get AI vacation plans!

There is also a setting where you access your user profile and update your travel preferences.

Settings

Facial Authentication with FACEIO before accessing the Vacation AI application

Chatting with the Vacation AI chatbot after Facial Authentication'

Próximos Passos

E é isso! Você acabou de construir o Vacation AI — um assistente de viagem seguro alimentado por um sistema de login facial usando o SDK de reconhecimento facial FACEIO e o chatbot LLaMA 3 do Groq. Essa arquitetura pode ser adaptada para outros casos de uso. Seja criativo. Você pode adicionar voz para texto para prompts de usuário para atualizar os recursos.

To learn more:

Para explorar o código ou executar o projeto localmente, siga estes passos::

git clone https://github.com/Tabintel/vacation-ai.git
cd vacation-ai-app
npm install
npm run dev
Enter fullscreen mode Exit fullscreen mode

🚀 Get the complete source code on GitHub.

Comece a construir aplicativos web seguros e amigáveis com autenticação facial para sites hoje!

Top comments (3)

Collapse
 
emiroberti profile image
Emiliano Roberti

excellent article

Collapse
 
envitab profile image
Ekemini Samuel

Thank you, Emiliano!!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.