C
ChowAPI
SDKs & Guides
Next.js

Use ChowAPI with Next.js

Fetch food nutrition data in Server Components, API Routes, and client-side with React Query.

Prerequisites

  • Node.js 18+
  • Next.js 14+ project
  • ChowAPI key (free at chowapi.dev/signup)

Installation

1

Install the SDK

npm install chowapi
2

Add your API key to .env.local

.env.local
CHOWAPI_KEY=chow_live_YOUR_KEY

Code examples

Search foods (Server Component)

Fetch food data at request time in a Server Component.

app/foods/page.tsx
import { ChowAPI } from 'chowapi'

const chow = new ChowAPI(process.env.CHOWAPI_KEY!)

export default async function FoodPage() {
  const { results } = await chow.search('chicken breast', { limit: 5 })

  return (
    <ul>
      {results.map(food => (
        <li key={food.id}>
          {food.name} - {food.nutrients.calories} cal,
          {food.nutrients.protein_g}g protein
        </li>
      ))}
    </ul>
  )
}

Barcode lookup (API Route)

Create an API route that proxies barcode lookups.

app/api/barcode/route.ts
import { ChowAPI } from 'chowapi'
import { NextResponse } from 'next/server'

const chow = new ChowAPI(process.env.CHOWAPI_KEY!)

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')

  if (!code) {
    return NextResponse.json({ error: 'Missing barcode' }, { status: 400 })
  }

  const food = await chow.barcode(code)
  return NextResponse.json(food)
}
Next.js Pattern

Client-side search with React Query

Use React Query for debounced, cached food search on the client.

components/FoodSearch.tsx
'use client'
import { useQuery } from '@tanstack/react-query'
import { ChowAPI } from 'chowapi'
import { useState } from 'react'

const chow = new ChowAPI(process.env.NEXT_PUBLIC_CHOWAPI_KEY!)

export function FoodSearch() {
  const [query, setQuery] = useState('')

  const { data, isLoading } = useQuery({
    queryKey: ['food-search', query],
    queryFn: () => chow.search(query, { limit: 8 }),
    enabled: query.length >= 2,
    staleTime: 60_000, // Cache results for 1 minute
  })

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)}
        placeholder="Search foods..." />
      {isLoading && <p>Searching...</p>}
      {data?.results.map(food => (
        <div key={food.id}>{food.name} - {food.nutrients.calories} cal</div>
      ))}
    </div>
  )
}

Start building

Credit packs from $5. Pay only for what you use.