{"id":16815,"library":"face-api.js","title":"Face API for JavaScript","description":"face-api.js is a robust JavaScript API designed for performing real-time face detection, face recognition, face landmark detection, face expression recognition, and age and gender estimation. It is built on top of the TensorFlow.js core library, enabling these advanced computer vision capabilities directly within web browsers and Node.js environments. The current stable version is 0.22.2. While a strict release cadence isn't explicitly stated, the project appears actively maintained with regular updates and tutorials, often aligning with TensorFlow.js advancements. Its key differentiator is providing a high-level, easy-to-use API over complex TensorFlow.js operations, simplifying the integration of sophisticated facial analysis features into JavaScript applications without requiring deep machine learning expertise. It also provides pre-trained models for various tasks, abstracting away the complexities of model management.","status":"active","version":"0.22.2","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","face","detection","recognition","tensorflow","tf","typescript"],"install":[{"cmd":"npm install face-api.js","lang":"bash","label":"npm"},{"cmd":"yarn add face-api.js","lang":"bash","label":"yarn"},{"cmd":"pnpm add face-api.js","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as the core TensorFlow.js library. A TF.js backend (e.g., @tensorflow/tfjs-backend-webgl or @tensorflow/tfjs-node) must also be installed and initialized based on the target environment.","package":"@tensorflow/tfjs-core","optional":false}],"imports":[{"note":"The library primarily uses a namespace import for its core functionality, providing access to all methods and utilities via `faceapi.*`.","wrong":"import faceapi from 'face-api.js'","symbol":"faceapi","correct":"import * as faceapi from 'face-api.js'"},{"note":"Provides access to the pre-trained neural networks (e.g., `nets.tinyFaceDetector`, `nets.faceRecognitionNet`) which must be loaded before use. These models reside under the `nets` export.","symbol":"nets","correct":"import { nets } from 'face-api.js'"},{"note":"Contains utility functions for visualizing detection results, landmarks, and expressions directly onto an HTML canvas element (e.g., `draw.drawDetections`, `draw.drawFaceLandmarks`).","symbol":"draw","correct":"import { draw } from 'face-api.js'"},{"note":"A utility function that creates an HTML canvas element from a media source (like an HTMLImageElement or HTMLVideoElement), useful for processing and drawing.","symbol":"createCanvasFromMedia","correct":"import { createCanvasFromMedia } from 'face-api.js'"}],"quickstart":{"code":"import * as faceapi from 'face-api.js';\n\nconst video = document.getElementById('video') as HTMLVideoElement;\nconst canvas = document.getElementById('overlay') as HTMLCanvasElement;\n\nasync function initializeFaceApi() {\n  // Ensure models are served from a public path (e.g., /models folder)\n  await Promise.all([\n    faceapi.nets.tinyFaceDetector.load('/models'),\n    faceapi.nets.faceLandmark68Net.load('/models'),\n    faceapi.nets.faceRecognitionNet.load('/models'),\n    faceapi.nets.faceExpressionNet.load('/models'),\n    faceapi.nets.ageGenderNet.load('/models')\n  ]);\n  console.log('All face-api.js models loaded successfully.');\n  startWebcamStream();\n}\n\nasync function startWebcamStream() {\n  try {\n    const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n    video.srcObject = stream;\n    video.onloadedmetadata = () => {\n      // Set canvas dimensions to match video\n      const displaySize = { width: video.width, height: video.height };\n      faceapi.matchDimensions(canvas, displaySize);\n      \n      setInterval(async () => {\n        const detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())\n          .withFaceLandmarks()\n          .withFaceExpressions()\n          .withAgeAndGender()\n          .withFaceDescriptors();\n\n        const resizedDetections = faceapi.resizeResults(detections, displaySize);\n        \n        canvas.getContext('2d')?.clearRect(0, 0, canvas.width, canvas.height);\n\n        faceapi.draw.drawDetections(canvas, resizedDetections);\n        faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);\n        faceapi.draw.drawFaceExpressions(canvas, resizedDetections);\n\n        resizedDetections.forEach(detection => {\n          const { age, gender, genderProbability } = detection;\n          new faceapi.draw.DrawTextField(\n            [\n              `${faceapi.utils.round(age, 0)} years`,\n              `${gender} (${faceapi.utils.round(genderProbability)})`\n            ],\n            detection.detection.box.bottomLeft\n          ).draw(canvas);\n        });\n\n      }, 100); // Run detection every 100ms\n    };\n  } catch (err) {\n    console.error(\"Error accessing webcam or initializing Face API:\", err);\n  }\n}\n\ndocument.addEventListener('DOMContentLoaded', initializeFaceApi);","lang":"typescript","description":"This quickstart initializes all necessary face-api.js models, starts a webcam stream, and continuously performs real-time face detection, landmark identification, expression recognition, and age/gender estimation, drawing the results onto an HTML canvas overlaid on the video feed."},"warnings":[{"fix":"Ensure the 'models' directory is served statically by your web server, and the `.load()` methods point to the correct URL (e.g., `faceapi.nets.modelName.load('/models')`).","message":"Model loading paths are crucial and frequently cause issues. Models must be hosted on a web server at a path accessible to your application (e.g., `/models`). Direct file system access will fail in browsers.","severity":"breaking","affected_versions":">=0.19.0"},{"fix":"For browsers, ensure `@tensorflow/tfjs-backend-webgl` is installed and initialized. For Node.js, use `@tensorflow/tfjs-node` or `@tensorflow/tfjs-node-gpu`. Opt for `TinyFaceDetectorOptions` for faster, albeit slightly less accurate, detections.","message":"Performance can vary drastically based on the client device's hardware (CPU/GPU) and the chosen TensorFlow.js backend. Using the 'tiny' models and WebGL backend is generally recommended for browsers.","severity":"gotcha","affected_versions":">=0.19.0"},{"fix":"At the top of your Node.js entry file, include `import '@tensorflow/tfjs-node';` or `require('@tensorflow/tfjs-node');` to activate the backend.","message":"If running in Node.js, you must explicitly import and register a TensorFlow.js backend (e.g., `require('@tensorflow/tfjs-node')` or `import '@tensorflow/tfjs-node'`) before loading any `face-api.js` models.","severity":"gotcha","affected_versions":">=0.19.0"},{"fix":"Always prefer ES Module `import * as faceapi from 'face-api.js'` for consistency and future compatibility, especially when using bundlers like Webpack or Vite.","message":"Older versions of face-api.js and its examples might use CommonJS `require()` syntax. While some versions might still support it, modern JavaScript applications and newer versions of the library primarily target ES Modules.","severity":"deprecated","affected_versions":"<0.22.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `@tensorflow/tfjs-backend-webgl` is installed and imported in your project (e.g., `import '@tensorflow/tfjs-backend-webgl';`). If running in Node.js, import `@tensorflow/tfjs-node` instead.","cause":"The TensorFlow.js WebGL backend was not imported or initialized, preventing GPU acceleration in the browser.","error":"Error: No backend registered for 'webgl'"},{"fix":"Verify that the 'models' directory is correctly placed in your public assets folder and served by your web server. The path provided to `load()` methods (e.g., `/models`) must match the actual URL where the model files are hosted.","cause":"The pre-trained models are not accessible at the specified path on the web server.","error":"Failed to load model from '/models/ssd_mobilenetv1_model_weights_manifest.json' - 404 Not Found"},{"fix":"Ensure you are using the correct `import * as faceapi from 'face-api.js'` syntax and that the import statement is executed before any `faceapi` calls. For CommonJS, use `const faceapi = require('face-api.js');` for older versions.","cause":"The `face-api.js` library or its `faceapi` namespace was not correctly imported or is not available in the current scope when trying to call its methods.","error":"TypeError: Cannot read properties of undefined (reading 'detectAllFaces') or 'faceapi is not defined'"},{"fix":"Ensure you are targeting an HTMLCanvasElement for drawing operations (e.g., `canvas.getContext('2d')`) and not an HTMLVideoElement.","cause":"Attempting to call `getContext` on a video element instead of a canvas element.","error":"TypeError: video.getContext is not a function"}],"ecosystem":"npm","meta_description":null}