Skip to main content
System Architecture
8 min read

Unitrition Architecture Deep-Dive: Engineering a Headless HealthTech & Precision Nutrition Platform with Next.js 16, WordPress & Supabase

Executive and technical breakdown of Unitrition (unitrition.info): decoupling WordPress CMS from Next.js 16 App Router, integrating USDA FoodData Central API for real-time Bread Units and glycemic curve modeling across 10 clinical diet frameworks, and securing user data with Supabase RLS.

AY
Artur Yusupov
Fullstack Web Engineer & AI Developer
Production Proof:Unitrition
Unitrition Architecture Deep-Dive: Engineering a Headless HealthTech & Precision Nutrition Platform with Next.js 16, WordPress & Supabase

1. Executive Summary & The HealthTech Challenge

Patients and health-conscious individuals managing strict dietary protocols (such as Type 1/Type 2 Diabetes, Ketogenic, Low-FODMAP, or Renal diets) face a daily cognitive burden: cross-referencing raw nutrition labels against complex clinical guidelines and manually calculating Bread Units (BU / Carbohydrate Exchanges) and glycemic load.

Meanwhile, traditional medical portals built on monolithic CMS templates suffer from slow mobile performance when querying large nutritional databases and lack interactive client-side modeling tools.

Unitrition (unitrition.info) was engineered to bridge clinical nutrition data and modern fullstack performance. By combining Headless WordPress, Next.js 16 App Router (React 19), Supabase PostgreSQL, and the U.S. Department of Agriculture (USDA) FoodData Central API, the platform delivers sub-second food compatibility scoring across 10 dietary frameworks, real-time Bread Units calculation, and interactive glycemic curve visualizations.


2. Architecture Decision Records (ADR - Why We Chose This Stack)

Architectural Decision
Hybrid Headless Stack (Next.js 16 + Headless WordPress REST API)
Rejected Alternative
Monolithic PHP WordPress Theme with Custom AJAX
Engineering & Business Rationale
Nutritionists and medical editors keep the familiar WordPress/ACF Pro editorial workflow, while end users get a blazing-fast React 19 App Router frontend with 95+ PageSpeed and zero PHP template bottlenecks.
Architectural Decision
Supabase PostgreSQL + Auth for User Profiles
Rejected Alternative
Storing User Accounts Inside WordPress wp_users
Engineering & Business Rationale
Decoupling user authentication and personal diet logs into Supabase with Row Level Security (RLS) prevents WordPress plugin vulnerabilities from ever exposing sensitive user health preferences.
Architectural Decision
Next.js Server-Side Proxy for USDA FoodData API
Rejected Alternative
Direct Client-Side fetch() to USDA API
Engineering & Business Rationale
Protects the private USDA API key from client exposure, normalizes inconsistent third-party JSON schemas on the server, and applies edge caching to prevent rate-limit exhaustion.
Architectural Decision
Bilingual Route & Schema.org Graph (`EN / ES`)
Rejected Alternative
Client-Only Translation Strings without URL Routing
Engineering & Business Rationale
Dedicated localized URLs with hreflang alternates and medical/nutrition Schema.org structured data maximize organic discovery across English and Spanish search markets.

3. Core Mechanisms: How Unitrition Works Under the Hood

Mechanism 1: The USDA FoodData Central Proxy & Nutrient Normalization Pipeline

The USDA FoodData Central database contains ratusan of thousands of food items (Foundation Foods, SR Legacy, Branded Foods), each reporting nutrients in slightly different nested structures and unit IDs (e.g., Energy in kcal vs kJ, Total Carbohydrate by difference, Dietary Fiber, Total Sugars).

When a user searches for an ingredient in Unitrition:

1
The client dispatches a debounced request to our internal Next.js Route Handler.
2
The server proxy authenticates with the USDA API using server-only environment credentials, extracts the raw nutrient array, and maps nutrient IDs into a strict, type-safe NormalizedFoodItem interface.
3
Responses are cached with stale-while-revalidate headers so popular food lookups resolve in under 30ms.
TS
// Conceptual blueprint of the Bread Units (BU) & Net Carbs calculation
export interface NormalizedMacros {
  caloriesKcal: number
  totalCarbsGrams: number
  dietaryFiberGrams: number
  sugarsGrams: number
  proteinGrams: number
  fatGrams: number
}

export function calculateBreadUnits(macros: NormalizedMacros, portionGrams: number) {
  const factor = portionGrams / 100
  const digestibleCarbs = Math.max(0, (macros.totalCarbsGrams - macros.dietaryFiberGrams) * factor)
  // 1 Bread Unit (BU) = 12g of digestible carbohydrates
  const breadUnits = Number((digestibleCarbs / 12).toFixed(2))
  return { digestibleCarbs: Number(digestibleCarbs.toFixed(1)), breadUnits }
}

Mechanism 2: Deterministic 10-Diet Traffic-Light Scoring Engine

Rather than relying on slow or unpredictable LLM calls to judge whether a food fits a diet, Unitrition uses a deterministic clinical rule matrix across 10 diet protocols:

  • Each diet profile defines strict macronutrient ratios, glycemic load ceilings, and excluded food groups.
  • When a user selects a diet plan and searches foods, the engine computes a color-coded compatibility score:
  • Green (Optimal Fit): Within macro targets and low glycemic impact.
  • Amber (Moderate / Portion Control): Requires strict portion scaling based on calculated Bread Units.
  • Red (Avoid): Exceeds carbohydrate/sodium/lipid thresholds for the active protocol.

Mechanism 3: Continuous Glucose Monitoring (CGM) Curve Simulation & PDF Export

To help users visualize *why* fiber and protein slow down glucose absorption compared to refined sugars, Unitrition includes an interactive Glycemic Response Simulator:

  • Based on the ratio of digestible carbohydrates, dietary fiber, fat, and protein in the selected portion, the engine models the projected postprandial glucose curve over a 180-minute window.
  • Users can compile their selected foods and meal calculations into a clean, print-ready PDF Nutrition Report directly in the browser.

Mechanism 4: Decoupled Editorial CMS via Headless WordPress & ISR

Educational nutrition articles and clinical guides are managed in a hardened headless WordPress instance using Advanced Custom Fields (ACF Pro):

  • Next.js fetches structured post payloads via the WP REST API during build and Incremental Static Regeneration (ISR).
  • Every article automatically generates Schema.org `Article` and `FAQPage` JSON-LD markup to capture medical and dietary search snippets.

4. Engineering Glossary: Every Key Term Explained

  • Headless CMS Architecture:
  • *What it is*: Separating the back-end content management panel (WordPress) from the front-end presentation layer (Next.js).
  • *Why it matters*: Content editors work in a familiar interface, while visitors experience instant React page transitions and superior security because the CMS admin panel is hidden from public traffic.
  • Incremental Static Regeneration (ISR):
  • *What it is*: A Next.js mechanism that updates static pages in the background after deployment when CMS content changes, without rebuilding the entire site.
  • *Why it matters*: Combines the speed of static HTML with the freshness of a dynamic database.
  • Bread Units (BU / Carbohydrate Exchange):
  • *What it is*: A clinical unit used in nutrition and diabetes management (1 BU equals 10g-12g of digestible carbohydrates) to estimate insulin requirements and glycemic impact.
  • *Why it matters*: Automating BU calculation across variable gram portions eliminates manual math errors for users.
  • Server-Side API Proxy:
  • *What it is*: An intermediate backend endpoint that forwards client requests to an external service (USDA API), attaches secret keys on the server, and sanitizes the response.
  • *Why it matters*: Prevents API key theft and insulates the frontend from third-party API breaking changes.
  • Supabase Row Level Security (RLS):
  • *What it is*: Fine-grained access control inside PostgreSQL that enforces auth.uid() = user_id on every database query.
  • *Why it matters*: Ensures one user can never read or modify another user's saved dietary profile.

5. Defense-in-Depth Security Posture

1
Zero-Trust Separation of CMS and User Data: Even if the editorial WordPress CMS were ever targeted, user accounts and personal dietary records reside in an isolated Supabase PostgreSQL cluster protected by RLS.
2
Server-Only Secret Isolation: USDA API keys and Supabase service keys are strictly confined to server-side environment variables and never bundled into client JavaScript.
3
Input Validation & Rate Protection: Search queries and calculator inputs are sanitized and debounced before hitting the server proxy, preventing upstream API quota exhaustion.
Battle-Tested Production Proof

Where This Architecture is Deployed in Production

These architectural patterns are not abstract theory - they are fully deployed and benchmarked in these live production builds:

Web Development in Seville & Spain / SMEs & Clinics

Custom Web Development for Businesses & Clinics in Seville & Spain

Fast, accessible, client-generating websites for businesses, clinics, and professional firms in Seville and across Spain. Zero slow page builders and zero hidden fees.

Explore B2B Service
Architecture Consulting

Planning a tech stack migration or new build?

Discuss architectural requirements with my interactive RAG AI assistant or connect directly for an engineering assessment.

Contact Directly