I've built face matching on Android before, on-device with TFLite and MobileFaceNet. When a project needed the same thing behind a Node.js backend, every option I looked at either sent users' photos to a third party, was painful to install, or used a model you can't ship commercially. So I wrote a small service the backend developer could run next to the app, then cleaned it up and open-sourced it as Face Match Service.
This post shows how to use it to add face sign-in to an Express app. It takes about an hour and runs on an ordinary CPU. No photo ever leaves your server.
By the end you'll have three routes (enrol a face, sign in with a selfie, delete a face) plus a short browser script that grabs a frame from the webcam. You'll need Node.js 18 or newer and Python 3.11 or newer. You don't need a GPU, Docker or a database server.
Why not a cloud API, or the face_recognition library?
Here's what's wrong with each of the usual options, at least for this job.
- Cloud face APIs send every photo to a third party, and you pay per call. Some won't let you identify people at all until you're approved. On Azure, Face Identify and Verify are Limited Access features, so you have to register and apply before you can use them.
- The face_recognition library sits on top of dlib, which usually wants CMake and a C++ compiler to install. On Windows that's a well-known headache. And even once it's installed, it's only a library. The HTTP API, storage, search and deletion are still yours to build.
- The most accurate pretrained models often can't be used commercially. InsightFace's model zoo, for example, is licensed for non-commercial research only.
Face Match Service gets around all of this with two small models from the OpenCV Model Zoo. YuNet finds the face (MIT licence) and SFace compares faces (Apache-2.0, 99.40% on the LFW benchmark). Together they come to about 39 MB, install with plain pip, and run on a CPU. For each face the service keeps a 128-number embedding in SQLite. The photo itself is thrown away.
How the pieces fit
The browser only ever talks to your Node backend. Your backend calls Face Match Service on 127.0.0.1, and the service answers with a user ID or "NOT_FOUND".
Browser ──► Express backend ──► Face Match Service (127.0.0.1:8000) ──► data/faces.db ▲ │ └── userId / "NOT_FOUND" ◄─┘ All the service knows about a user is an ID string. Users, passwords and sessions stay in your backend, where they already live.
One decision here matters a lot for security. In this tutorial the user types their email first, and the face check only confirms it. You could instead match the face against every enrolled user (1:N) and log in whoever comes back. That's convenient, but it means anyone with a decent photo of one of your users can try their luck. Checking the face against the one account being claimed is a much smaller target. The service supports both, and I cover the kiosk-style 1:N version at the end of step 4.
Step 1: Run Face Match Service
Clone the repo, set up a virtual environment, and download the two models. You only need to download them once (about 39 MB), and the script checks their checksums.
git clone https://github.com/Mihir7027/face-match-service.git cd face-match-service python3 -m venv .venv .venv/bin/pip install -r requirements.txt .venv/bin/python scripts/download_models.py cp .env.example .env .venv/bin/uvicorn app.main:app --env-file .env --host 127.0.0.1 --port 8000 On Windows, swap in .venv\Scripts\pip and .venv\Scripts\python. Then check that it's running:
curl http://127.0.0.1:8000/health There are interactive API docs at http://127.0.0.1:8000/docs as well. Leave --host 127.0.0.1 as it is. The service has no authentication, so the only thing that should be able to reach it is your backend on the same machine.
Step 2: Write a small Node client
In your Express project, install the three packages we'll use:
npm install express multer express-session Next, create faceClient.js. It only uses fetch, FormData and Blob, which are built into Node 18, so there's nothing else to install. The repo has a fuller version with a health check in examples/node.
// faceClient.js const FACE_URL = process.env.FACE_URL || 'http://127.0.0.1:8000'; class FaceServiceError extends Error { constructor(message, code, status) { super(message); this.code = code; // NO_FACE, MULTIPLE_FACES, FACE_TOO_SMALL, ... this.status = status; // HTTP status from the service, 503 if unreachable } } async function request(method, path, form) { let res; try { res = await fetch(FACE_URL + path, { method, body: form, signal: AbortSignal.timeout(10000) }); } catch (err) { throw new FaceServiceError(`Face service unreachable: ${err.message}`, 'SERVICE_UNAVAILABLE', 503); } const body = await res.json().catch(() => ({})); if (!res.ok) throw new FaceServiceError(body.message || 'Face service error', body.error, res.status); return body; } function imageForm(buffer, fields) { const form = new FormData(); form.append('image', new Blob([buffer]), 'image.jpg'); for (const [key, value] of Object.entries(fields)) form.append(key, String(value)); return form; } const enrollFace = (userId, buffer) => request('POST', '/enroll', imageForm(buffer, { userId })); const identifyFace = (buffer) => request('POST', '/identify', imageForm(buffer, {})); const forgetFace = (userId) => request('DELETE', `/faces/${encodeURIComponent(userId)}`); module.exports = { enrollFace, identifyFace, forgetFace, FaceServiceError }; identifyFace gives you back { userId, matched, score, reason, facesDetected, matches }. The matches array holds every enrolled user above the threshold, best match first.
Step 3: Enrol a face from the user's settings page
Users switch face sign-in on from their settings, after logging in the normal way. That way nobody can enrol a face on someone else's account. Set up sessions and uploads once in server.js:
// server.js const express = require('express'); const session = require('express-session'); const multer = require('multer'); const { enrollFace, identifyFace, forgetFace, FaceServiceError } = require('./faceClient'); const app = express(); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax', secure: process.env.NODE_ENV === 'production' }, })); const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 8 * 1024 * 1024 } }); function requireLogin(req, res, next) { if (!req.session.userId) return res.status(401).json({ error: 'LOGIN_REQUIRED' }); next(); } The enrol route hands the uploaded photo straight to the service. Multer keeps it in memory, so it never touches the disk:
app.post('/api/me/face', requireLogin, upload.single('image'), async (req, res, next) => { try { if (!req.file) return res.status(400).json({ error: 'IMAGE_REQUIRED' }); await enrollFace(req.session.userId, req.file.buffer); res.json({ ok: true }); } catch (err) { next(err); } }); If a photo is no good, the service tells you why with a code: NO_FACE, MULTIPLE_FACES or FACE_TOO_SMALL. Your UI can turn those into something friendlier. Add an error handler at the end of server.js to pass them through:
app.use((err, req, res, next) => { if (err instanceof FaceServiceError) { const status = err.status >= 500 ? 503 : 400; return res.status(status).json({ error: err.code, message: err.message }); } next(err); }); Calling /api/me/face again replaces the old face. So if a user wants a new photo on file, they just enrol again.
Step 4: Sign in with a selfie
On the login page, the user enters their email and the browser sends it along with a webcam frame. The backend finds the account, asks the service who's in the photo, and signs the user in only if the best match is that same account:
const RETAKE = new Set(['NO_FACE', 'MULTIPLE_FACES']); app.post('/api/login/face', upload.single('image'), async (req, res, next) => { try { const user = await findUserByEmail(req.body.email); // your existing lookup if (!user || !req.file) return res.status(401).json({ error: 'LOGIN_FAILED' }); const result = await identifyFace(req.file.buffer); const best = result.matches[0]; if (!best || best.userId !== user.id) { // Only say why when the fix is a retake; never hint at other accounts. const reason = RETAKE.has(result.reason) ? result.reason : undefined; return res.status(401).json({ error: 'LOGIN_FAILED', reason }); } req.session.regenerate((err) => { if (err) return next(err); req.session.userId = user.id; res.json({ ok: true, user: { id: user.id, name: user.name } }); }); } catch (err) { next(err); } }); A few things in there are easy to miss:
-
req.session.regenerategives the user a new session ID when they log in, which protects you from session fixation. - User IDs can be up to 128 characters of letters, digits and
_ . : @ -, so UUIDs and numeric IDs work without changes. - When someone deletes their account, call
forgetFace(user.id)so their embedding goes with it.
If you're building a check-in desk or an attendance kiosk where nobody types an email, skip the lookup and work with result.matches directly. When it holds more than one user, those people look alike to the model. Show their names and photos and let a staff member pick the right one. The repo's Express example does exactly this.
Step 5: Capture a frame in the browser
The login page shows a live camera preview. When the user hits submit, it grabs one frame as a JPEG and posts it with the email:
<form id="face-login"> <input type="email" name="email" required placeholder="you@example.com"> <video id="camera" autoplay playsinline muted></video> <button type="submit">Sign in with my face</button> <p id="message"></p> </form> <script> const video = document.getElementById('camera'); const message = document.getElementById('message'); navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then((stream) => { video.srcObject = stream; }) .catch(() => { message.textContent = 'Camera unavailable. Use your password instead.'; }); function captureFrame() { const canvas = document.createElement('canvas'); canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); return new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.92)); } const MESSAGES = { NO_FACE: "We couldn't see a face. Look at the camera and try again.", MULTIPLE_FACES: 'Make sure only you are in the frame.', }; document.getElementById('face-login').addEventListener('submit', async (event) => { event.preventDefault(); const form = new FormData(event.target); form.append('image', await captureFrame(), 'capture.jpg'); const res = await fetch('/api/login/face', { method: 'POST', body: form }); const data = await res.json(); if (res.ok) { window.location.href = '/'; } else { message.textContent = MESSAGES[data.reason] || 'Face sign-in failed. Try again or use your password.'; } }); </script> Browsers only allow camera access on https:// pages and on localhost. You'll get better matches if users face the camera in decent light, with no sunglasses or mask. A face that's roughly 150 pixels wide or bigger works well.
Before you ship it
- Keep the service private. Bind it to
127.0.0.1, let only your backend call it, and never open port 8000 to the internet, because there's no authentication. If you want to run it under systemd, the repo's integration guide has a unit file. - Don't make the face the only way in. Face Match Service can't tell a live person from a printed photo or a phone screen. Keep a password or passkey option, and add a liveness check before you use faces for anything sensitive.
- Rate-limit
/api/login/face. A package likeexpress-rate-limitstops people from throwing photo after photo at it. - Tune the threshold with your own photos. The default cosine similarity threshold is
0.40, a little stricter than OpenCV's suggested 0.363 for SFace. Raise it if a wrong match would be costly, and lower it if your users have poor cameras. The setting isFACE_MATCH_THRESHOLDin.env. - Ask for consent, and delete when asked. Face embeddings are biometric data, and laws like the GDPR, Illinois' BIPA and India's DPDP Act apply to them. Make face sign-in opt-in, tell users what you store, and call
forgetFacewhen they turn it off or close their account. - Back up
data/faces.db. It's a single SQLite file. Also run only one service process per database, since search uses an in-memory index.
FAQ
Does face sign-in work offline?
Yes. Once the models are downloaded, the service doesn't make any network calls. It all runs on your own server.
Is it free for commercial use?
Yes. The service is MIT-licensed, YuNet is MIT and SFace is Apache-2.0, so you can use all three in commercial products.
Does it store users' photos?
No. Each photo becomes a 128-number embedding in memory and is then dropped. Only the embedding and the user ID get saved.
How accurate is it?
In OpenCV's own evaluation, SFace scores 99.40% on the LFW benchmark. Your real results will depend on lighting, camera quality and head angle, so test with photos from your actual users.
Can someone log in with a photo of me?
Possibly, yes. There's no liveness detection, so a good photo could get past the face check. That's why this setup asks for the email first and keeps a password option. For anything sensitive, I'd also add rate limiting and a liveness check.
Can I use it from Python, PHP or Go instead of Node?
Yes. It's a plain HTTP API that takes multipart/form-data uploads, so anything with an HTTP client can call it. Once it's running, the interactive docs at /docs list every endpoint.
Wrapping up
So that's face sign-in with roughly 100 lines of backend code, and no user photos leaving your server.
What I'd really like to hear is where it falls over, especially with bad lighting, cheap webcams or a large number of enrolled users. Those cases are hard for me to test on my own.
The code is on GitHub at github.com/Mihir7027/face-match-service under the MIT licence. Issues, questions and pull requests are all welcome. And if it saves you some time, a star helps other people find it.
Mihir7027 / face-match-service
Self-hosted face recognition REST API in Python (FastAPI + OpenCV). Enrol a face, then identify who is in any photo: returns their userId or NOT_FOUND. CPU only, no GPU, Docker or DB server. Stores embeddings, never photos. Commercial-friendly models (YuNet MIT, SFace Apache-2.0).
I used AI assistance while building the project and drafting this tutorial.
