> ## Documentation Index
> Fetch the complete documentation index at: https://docs.brandfetch.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Brandfetch returns real company logos, brand data, and brand context. It does not design, generate, or edit logos.
> To show a logo in a user interface, use the Logo API as an image URL in an <img> tag, such as https://cdn.brandfetch.io/domain/{domain}?c={CLIENT_ID}. The client ID is public and belongs in frontend code. Never download, proxy, re-host, or optimize these images on a server, because requests that look programmatic are redirected with automated_traffic. In Next.js, this means next/image needs a custom loader or the unoptimized prop.
> To turn a company name that a user types into a domain, use the Brand Search API with the same client ID, and keep only the domain the user picks.
> For colors, fonts, downloadable logo files, and company data as JSON, call the Brand API from a server with the header Authorization: Bearer {API_KEY}, reading the key from an environment variable and never exposing it to the browser. Prefer typed routes such as /v2/brands/domain/{domain} and /v2/brands/ticker/{ticker} over the auto-detect route /v2/brands/{identifier}.
> Use the Brand Context API for a written summary of what a company does, who it sells to, and how it sounds, and the Transaction API to identify the merchant behind a card or bank transaction label.
> When a request fails, branch on the x-bf-error header code rather than on the status code or the message text. Every code, and what to do about it, is listed at https://docs.brandfetch.com/concepts/errors.
> Requests for brandfetch.com are free on the Brand API and Brand Context API, so use that domain in tests and examples.
> Brand API responses can be cached for up to 30 days, while Logo API images must be hotlinked rather than stored and Brand Search results must not be stored at all. See https://docs.brandfetch.com/concepts/caching.
> If the user has no credentials yet, https://brandfetch.com/auth.md explains how they get a client ID and an API key. An agent without an account can pay $0.10 per Brand API, Brand Context API, or Transaction API request with x402 or MPP, as described at https://docs.brandfetch.com/agents/pay-per-request.

# Company logos in Next.js

> Show company logos in a Next.js app with next/image and a custom loader, add a company autocomplete, and fetch brand colors and fonts from a Server Component or Route Handler.

A Next.js app usually needs Brandfetch in two places: logos in the browser, which come from the [Logo API](https://docs.brandfetch.com/logo-api/overview.md) and a public client ID, and brand data on the server, which comes from the [Brand API](https://docs.brandfetch.com/brand-api/overview.md) and a secret API key. This page covers both, along with the one setting that trips up most Next.js projects, which is that the default `next/image` optimizer has to be swapped for a custom loader before Brandfetch logos will load.

If you would rather install ready-made components, the [shadcn/ui registry](https://docs.brandfetch.com/integrations/shadcn.md) adds a logo, a company search, a logo wall, and a brand card to your project with one command.

## Add your credentials

Put both credentials in `.env.local`. The client ID carries the `NEXT_PUBLIC_` prefix because the browser needs it, while the API key has no prefix, so Next.js keeps it on the server and never ships it in the client bundle:

```bash .env.local theme={null}
NEXT_PUBLIC_BRANDFETCH_CLIENT_ID=your-client-id
BRANDFETCH_API_KEY=your-api-key
```

You can get the client ID in the [developer dashboard](https://developers.brandfetch.com/register), and the API key on the [API keys page](https://developers.brandfetch.com/dashboard/keys). If you only show logos, the client ID is all you need.

## Show a logo with next/image

By default, `next/image` downloads every remote image on your server, resizes it, and serves the copy from `/_next/image`. The Logo API treats that server-side download as programmatic access and answers it with an `automated_traffic` redirect instead of the logo, and serving the resized copy from your own domain would also count as re-hosting, which the [caching rules](https://docs.brandfetch.com/concepts/caching.md) don't allow.

A custom `loader` fixes both problems. It tells `next/image` to build each image URL itself, so the browser requests the logo straight from Brandfetch's CDN, and the CDN does the resizing through the `w` and `h` options. You keep the lazy loading, the `srcset`, and the layout-shift protection that `next/image` gives you:

```tsx components/company-logo.tsx theme={null}
"use client";

import Image, { type ImageLoaderProps } from "next/image";

const clientId = process.env.NEXT_PUBLIC_BRANDFETCH_CLIENT_ID;

function brandfetchLoader({ src, width }: ImageLoaderProps) {
  return `https://cdn.brandfetch.io/domain/${src}/w/${width}/h/${width}/fallback/lettermark/icon?c=${clientId}`;
}

export function CompanyLogo({ domain, size = 32 }: { domain: string; size?: number }) {
  return (
    <Image
      loader={brandfetchLoader}
      src={domain}
      alt={`${domain} logo`}
      width={size}
      height={size}
    />
  );
}
```

You can then use it anywhere, including in Server Components:

```tsx app/customers/page.tsx theme={null}
import { CompanyLogo } from "@/components/company-logo";

export default function Customers() {
  return <CompanyLogo domain="nike.com" size={48} />;
}
```

The component is marked `"use client"` because a loader is a function, and Next.js can't pass a function from a Server Component to `next/image`. You don't need to add `cdn.brandfetch.io` to `images.remotePatterns` either, since that list only applies to images the optimizer downloads, and with a loader it downloads nothing.

The loader above asks for the square icon with a lettermark when a brand has no icon. To show the full horizontal logo instead, end the URL with `/logo` instead of `/icon`, and drop the `h` option so the logo keeps its proportions. Every option is listed in [Logo API parameters](https://docs.brandfetch.com/logo-api/parameters.md).

## Or use a plain img tag

If you don't need responsive sizes, a plain `<img>` tag works in any component, server or client, with no configuration at all. Ask for twice the display size so the logo stays sharp on high-density screens:

```tsx theme={null}
<img
  src={`https://cdn.brandfetch.io/domain/nike.com/w/64/h/64/icon?c=${process.env.NEXT_PUBLIC_BRANDFETCH_CLIENT_ID}`}
  alt="Nike logo"
  width={32}
  height={32}
/>
```

Next.js lint flags `<img>` with the `@next/next/no-img-element` rule, which you can turn off for this line. Setting `unoptimized` on `next/image` has the same effect as a plain tag, if you'd rather keep the component.

Whichever you choose, leave the browser's default referrer policy in place. The Logo API needs the `Referer` header to know which site is showing the logo, so a `Referrer-Policy: no-referrer` set in `next.config.js` or in middleware stops logos from loading. The [usage guidelines](https://docs.brandfetch.com/logo-api/overview.md#usage-guidelines) list the policies that work.

## Add a company autocomplete

Users type company names rather than domains, so a company field needs the [Brand Search API](https://docs.brandfetch.com/brand-search-api/overview.md) to turn what they type into a domain. It uses the same public client ID, so the request runs in the browser. Debounce it to stay well inside the [rate limits](https://docs.brandfetch.com/concepts/limits-and-billing.md), and keep only the domain the user picks:

```tsx components/company-search.tsx theme={null}
"use client";

import { useEffect, useState } from "react";

type Brand = { name: string; domain: string; icon: string; brandId: string };

export function CompanySearch({ onSelect }: { onSelect: (domain: string) => void }) {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<Brand[]>([]);

  useEffect(() => {
    if (query.trim().length < 2) return setResults([]);
    const controller = new AbortController();
    const timer = setTimeout(async () => {
      try {
        const res = await fetch(
          `https://api.brandfetch.io/v2/search/${encodeURIComponent(query)}?c=${process.env.NEXT_PUBLIC_BRANDFETCH_CLIENT_ID}`,
          { signal: controller.signal }
        );
        setResults(res.ok ? await res.json() : []);
      } catch (err) {
        if (!controller.signal.aborted) setResults([]);
      }
    }, 250);
    return () => {
      clearTimeout(timer);
      controller.abort();
    };
  }, [query]);

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Company name" />
      <ul>
        {results.map((brand) => (
          <li key={brand.brandId}>
            <button type="button" onClick={() => onSelect(brand.domain)}>
              <img src={brand.icon} alt="" width={20} height={20} />
              {brand.name} <span>{brand.domain}</span>
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
```

Each new keystroke aborts the previous request, so a slow earlier response can't overwrite newer results, and a failed search clears the list rather than leaving old matches the user could pick by mistake. The [company autocomplete](https://docs.brandfetch.com/use-cases/company-autocomplete.md) use case covers keyboard navigation and empty states, and the shadcn registry has a styled version as its `brand-search` component.

## Fetch brand data on the server

Colors, fonts, downloadable logo files, and company details come from the Brand API, which needs the secret API key, so call it only from server code. Keeping the call in one module that imports `server-only` makes the build fail if a client component ever imports it by mistake:

```ts lib/brandfetch.ts theme={null}
import "server-only";

export async function getBrand(domain: string) {
  const res = await fetch(`https://api.brandfetch.io/v2/brands/domain/${domain}`, {
    headers: { Authorization: `Bearer ${process.env.BRANDFETCH_API_KEY}` },
    next: { revalidate: 60 * 60 * 24 * 7 },
  });

  if (!res.ok) {
    console.warn(`Brandfetch ${res.status}: ${res.headers.get("x-bf-error")}`);
    return null;
  }
  return res.json();
}
```

The `revalidate` option refreshes each response in the Next.js data cache after seven days, so repeat visits don't use a credit. It isn't a hard expiry, though, because Next.js keeps serving the old response while it refreshes, keeps it when a refresh fails, and doesn't delete entries nobody requests. Since [Brand API data can be cached](https://docs.brandfetch.com/concepts/caching.md) for 30 days at most, store brands in your own database with an expiry or a scheduled cleanup when you need to guarantee that limit. You can install the `server-only` package with `npm install server-only`.

A Server Component can then render brand data directly, without any client-side request:

```tsx app/brands/[domain]/page.tsx theme={null}
import { getBrand } from "@/lib/brandfetch";
import { notFound } from "next/navigation";

export default async function BrandPage({ params }: { params: Promise<{ domain: string }> }) {
  const { domain } = await params;
  const brand = await getBrand(domain);
  if (!brand) notFound();

  return (
    <main>
      <h1>{brand.name}</h1>
      <p>{brand.description}</p>
      <ul>
        {brand.colors.map((color: { hex: string; type: string }) => (
          <li key={color.hex} style={{ color: color.hex }}>{color.type}: {color.hex}</li>
        ))}
      </ul>
    </main>
  );
}
```

When client code needs brand data, for example after the user picks a company in the autocomplete, expose it through a Route Handler, so the key stays on the server and the browser only ever talks to your own endpoint:

```ts app/api/brand/[domain]/route.ts theme={null}
import { getBrand } from "@/lib/brandfetch";

export async function GET(_req: Request, { params }: { params: Promise<{ domain: string }> }) {
  const { domain } = await params;
  const brand = await getBrand(domain);
  if (!brand) return Response.json({ error: "brand_not_found" }, { status: 404 });

  return Response.json({ name: brand.name, colors: brand.colors, fonts: brand.fonts });
}
```

While you build, use `brandfetch.com` as the domain, because lookups for it are free on the Brand API. When a request fails, the `x-bf-error` header names the reason with a stable code, such as `quota_exceeded` or `domain_unresolvable`, and [errors](https://docs.brandfetch.com/concepts/errors.md) explains what to do about each one.

## Prompt for coding agents

If you build with Cursor, Claude Code, or another coding agent, paste this prompt so it follows the same rules:

```text theme={null}
Add Brandfetch to this Next.js app.
Logos: build a "use client" CompanyLogo component that uses next/image with a custom loader returning https://cdn.brandfetch.io/domain/{domain}/w/{width}/h/{width}/fallback/lettermark/icon?c={NEXT_PUBLIC_BRANDFETCH_CLIENT_ID}. Never let the default optimizer, a route handler, or a script download Logo API images, and do not add remotePatterns.
Company search: call https://api.brandfetch.io/v2/search/{query}?c={NEXT_PUBLIC_BRANDFETCH_CLIENT_ID} from the browser with a 250ms debounce, and store only the domain the user picks.
Brand data: call https://api.brandfetch.io/v2/brands/domain/{domain} only from server code, in a lib/brandfetch.ts module that imports "server-only", with Authorization: Bearer {BRANDFETCH_API_KEY} and next: { revalidate: 604800 }. Never prefix the API key with NEXT_PUBLIC_.
On errors, log the x-bf-error response header. Docs: https://docs.brandfetch.com/llms.txt
```

The [build with AI](https://docs.brandfetch.com/build-with-ai.md) page covers the Brandfetch MCP server and the docs MCP, which give agents live access to brand data and to these docs.

## FAQ

> [accordion] Why don't Brandfetch logos load with next/image?
>
> The default `next/image` optimizer downloads images on your server, and the Logo API redirects server-side requests with `automated_traffic` instead of returning the logo. Add a custom `loader` that returns the Brandfetch URL, or set `unoptimized`, so the browser loads the logo directly from the CDN.

> [accordion] Do I need to add cdn.brandfetch.io to remotePatterns?
>
> No. The `images.remotePatterns` list only applies to images that the Next.js optimizer downloads, and with a custom loader or `unoptimized` it doesn't download Brandfetch images at all.

> [accordion] Can the API key use the NEXT\_PUBLIC\_ prefix?
>
> No. Anything prefixed with `NEXT_PUBLIC_` is bundled into the JavaScript that ships to the browser, where anyone can read it. Only the client ID belongs there, and the API key should stay in a server-only module.

> [accordion] Can I cache Brandfetch logos in Next.js?
>
> Logo API images must be hotlinked from the CDN, so don't download or store them, although the browser cache handles repeat views on its own. Brand API responses, including the logo files they link to, can be cached for up to 30 days, which the `revalidate` option above already does. See [caching](https://docs.brandfetch.com/concepts/caching.md).

> [accordion] Does this work with the Pages Router?
>
> Yes. The `CompanyLogo` and `CompanySearch` components work as they are, because the Pages Router simply ignores the `"use client"` line. Call `getBrand` from `getServerSideProps`, `getStaticProps`, or an API route under `pages/api` after removing its `import "server-only"` line, which only works in the App Router, and use `revalidate` in `getStaticProps` instead of the fetch option.

## Related

> [card] [shadcn/ui components](https://docs.brandfetch.com/integrations/shadcn.md)
>
> Ready-made logo, search, logo wall, and brand card components for React.

> [card] [Company autocomplete](https://docs.brandfetch.com/use-cases/company-autocomplete.md)
>
> A complete company field, from the first keystroke to the saved domain.

> [card] [Logo API parameters](https://docs.brandfetch.com/logo-api/parameters.md)
>
> Sizes, themes, fallbacks, and logo types for every image URL.

> [card] [Caching](https://docs.brandfetch.com/concepts/caching.md)
>
> What you can store from each API, and for how long.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.