What we’re building
A calorie tracker that lets users search for foods, log meals, and see their daily nutrition totals. We’ll use vanilla JavaScript and the FoodBase API to keep things simple and framework-agnostic.
By the end of this tutorial, you’ll have a working app that:
- Searches our 6.1M food product database
- Displays nutrition info per serving
- Tracks daily calorie and macro totals
Prerequisites
- A FoodBase account (sign up free)
- An API key from the dashboard
- Basic JavaScript knowledge
Step 1: Set up the API client
Create a reusable function to call the API:
const API_KEY = "food_your_key_here";
const BASE_URL = "https://foodbase.dev/v1";
async function foodApi(path) {
const res = await fetch(`${BASE_URL}${path}`, {
headers: { "X-API-Key": API_KEY },
});
if (!res.ok) {
const err = await res.json();
throw new Error(err.error || `HTTP ${res.status}`);
}
return res.json();
}
Step 2: Search for foods
Let users search by name. The API returns results ranked by relevance:
async function searchFoods(query, limit = 10) {
const params = new URLSearchParams({ q: query, limit });
const data = await foodApi(`/foods/search?${params}`);
return data.data; // array of food items
}
// Usage
const results = await searchFoods("chicken breast");
console.log(`Found ${results.length} results`);
results.forEach(food => {
console.log(`${food.name_default} (${food.brand || "Generic"})`);
});
Step 3: Get nutrition details
When the user selects a food, fetch its full details including the nutrition summary:
async function getFoodWithNutrition(foodId) {
return foodApi(`/foods/${foodId}`);
}
const food = await getFoodWithNutrition("abc-123");
console.log(`${food.name_default}: ${food.nutrition_summary.energy_kcal} kcal/100g`);
The nutrition_summary includes the 6 most common macros: energy_kcal, proteins_g, carbs_g, fat_g, sugars_g, and fiber_g.
Step 4: Calculate per serving
The API returns all values per 100g. To calculate per serving, multiply by the serving weight:
function calculateServing(nutritionPer100g, servingGrams) {
if (!nutritionPer100g) return null;
const factor = servingGrams / 100;
return {
calories: Math.round((nutritionPer100g.energy_kcal || 0) * factor),
protein: round1((nutritionPer100g.proteins_g || 0) * factor),
carbs: round1((nutritionPer100g.carbs_g || 0) * factor),
fat: round1((nutritionPer100g.fat_g || 0) * factor),
fiber: round1((nutritionPer100g.fiber_g || 0) * factor),
};
}
function round1(n) {
return Math.round(n * 10) / 10;
}
// Example: 100g chicken breast
const serving = calculateServing(food.nutrition_summary, 150);
// → { calories: 248, protein: 46.5, carbs: 0, fat: 5.3, fiber: 0 }
Step 5: Track daily meals
Store logged meals and compute running totals:
const meals = [];
function addMeal(food, servingGrams) {
const nutrition = calculateServing(food.nutrition_summary, servingGrams);
meals.push({
name: food.name_default,
brand: food.brand,
grams: servingGrams,
...nutrition,
addedAt: new Date(),
});
return nutrition;
}
function getDailyTotals() {
return meals.reduce(
(totals, meal) => ({
calories: totals.calories + (meal.calories || 0),
protein: round1(totals.protein + (meal.protein || 0)),
carbs: round1(totals.carbs + (meal.carbs || 0)),
fat: round1(totals.fat + (meal.fat || 0)),
fiber: round1(totals.fiber + (meal.fiber || 0)),
}),
{ calories: 0, protein: 0, carbs: 0, fat: 0, fiber: 0 },
);
}
// Log a meal
addMeal(food, 150);
console.log(getDailyTotals());
// → { calories: 248, protein: 46.5, carbs: 0, fat: 5.3, fiber: 0 }
Step 6: Add barcode scanning
If your app has camera access, you can scan barcodes and look up products instantly:
async function lookupBarcode(barcode) {
try {
return await foodApi(`/foods/barcode/${barcode}`);
} catch (err) {
if (err.message.includes("Not found")) {
return null; // Product not in database
}
throw err;
}
}
// After scanning a barcode with a camera library
const product = await lookupBarcode("5449000000996");
if (product) {
console.log(`Found: ${product.name_default} by ${product.brand}`);
// → "Found: Original Taste by Coca-Cola"
}
Step 7: Persist data
For a real app, you’ll want to save meal history. Here’s a simple localStorage approach:
function saveMeals() {
localStorage.setItem("meals", JSON.stringify(meals));
localStorage.setItem("mealsDate", new Date().toISOString().slice(0, 10));
}
function loadMeals() {
const today = new Date().toISOString().slice(0, 10);
const savedDate = localStorage.getItem("mealsDate");
if (savedDate === today) {
const saved = localStorage.getItem("meals");
return saved ? JSON.parse(saved) : [];
}
// New day — reset
return [];
}
Tips for production apps
- Cache search results on the client to reduce API calls when users re-search the same terms
- Use the bulk endpoint when loading meal history — fetch all food details in one request instead of N individual calls
- Set daily goals and show progress bars (common targets: 2000 kcal, 50g protein, 25g fiber)
- Handle offline gracefully — cache recently viewed foods so the app works without network
- Monitor your usage in the dashboard to stay within your plan limits
Bonus: log meals from a photo
If you have AI credits to spend (every plan includes some), the meal endpoint turns a plate photo into logged items with portion estimates — a much lower-friction way to log than searching:
async function analyzeMealPhoto(file) {
const form = new FormData();
form.append("image", file);
const res = await fetch("https://foodbase.dev/v1/vision/meal", {
method: "POST",
headers: { "X-API-Key": API_KEY },
body: form,
});
if (!res.ok) throw new Error(`Vision error: ${res.status}`);
const meal = await res.json();
// meal.items: [{ dish, portion_g_est, match: { estimated_kcal, ... } }]
// meal.estimated_total_kcal: number | null
return meal;
}
Portion sizes are AI estimates from a single photo, so treat the numbers as a starting point the user can adjust — the response ships a disclaimer string you should show. Try it first in the photo playground.
Next steps
- Add a meal planning feature using saved foods and target macros
- Integrate with a fitness tracker API to factor in exercise
- Build a recipe calculator that sums nutrients across multiple ingredients
- Use the detailed nutrients endpoint for micronutrient tracking (vitamins, minerals)
Keep reading
Build it with FoodBase
6.1M products, 40+ nutrients and AI food analysis — free to start, no credit card.