Car logos in React
One small client file and one component. The component renders the right CDN size for the slot, lazy-loads, and falls back to the brand initial if the image fails. Make lists come from your backend so the secret key never reaches the browser.
The code on this page is the code our CI runs against recorded API responses.
1. Add your keys
| Variable | Value | Used for |
|---|---|---|
| VITE_MOTOMARKS_PUBLIC_KEY | pk_… | Publishable key, passed to BrandLogo as publicKey |
2. Add the code
Builds CDN URLs, picks the smallest sharp size, and wraps the JSON API with typed errors. Framework-free, so the same file works in every JavaScript example.
// Minimal client for the Motomarks JSON API and image CDN.
// pk_ keys are publishable (browser, CDN URLs); sk_ keys are secret (server only).
const API_BASE = "https://motomarks.io/api/v1";
const CDN_BASE = "https://motomarks.io/img";
export type LogoType = "full" | "badge" | "wordmark";
export type LogoSize = "xs" | "sm" | "md" | "lg" | "xl";
export interface LogoOptions {
type?: LogoType;
size?: LogoSize;
format?: "png" | "webp";
aspect?: "square" | "height";
}
const SIZE_PIXELS: Record<LogoSize, number> = { xs: 64, sm: 128, md: 256, lg: 512, xl: 1024 };
/** Smallest preset that stays sharp at `cssPixels` on a `dpr` screen. */
export function sizeFor(cssPixels: number, dpr = 2): LogoSize {
const needed = cssPixels * dpr;
const match = (Object.keys(SIZE_PIXELS) as LogoSize[]).find((size) => SIZE_PIXELS[size] >= needed);
return match ?? "xl";
}
/** Image CDN URL for a brand slug. Defaults: full logo, md (256px), WebP, square. */
export function logoUrl(slug: string, publicKey: string, options: LogoOptions = {}): string {
const params = new URLSearchParams();
if (options.type && options.type !== "full") params.set("type", options.type);
if (options.size && options.size !== "md") params.set("size", options.size);
if (options.format && options.format !== "webp") params.set("format", options.format);
if (options.aspect && options.aspect !== "square") params.set("aspect", options.aspect);
params.set("token", publicKey);
return `${CDN_BASE}/${encodeURIComponent(slug)}?${params}`;
}
export interface Brand {
id: string;
slug: string;
brandName: string;
companyName: string | null;
country: string | null;
parentCompany: string | null;
foundedYear: string | null;
officialDomain: string | null;
color: string | null;
colors: string[];
vehicleTypes: string[];
updatedAt: string;
}
export class MotomarksError extends Error {
constructor(
readonly status: number,
readonly code: string,
message: string,
) {
super(message);
this.name = "MotomarksError";
}
}
async function request<T>(path: string, secretKey: string, fetchImpl: typeof fetch): Promise<T> {
const response = await fetchImpl(`${API_BASE}${path}`, {
headers: { Authorization: `Bearer ${secretKey}` },
});
const body = await response.json().catch(() => ({}));
if (!response.ok) {
// 401 bad key, 403 plan or domain restriction, 404 unknown slug,
// 429 free-plan daily limit. `code` is set for 403 and 429.
throw new MotomarksError(response.status, body.code ?? body.error ?? "HTTP_ERROR", body.message ?? response.statusText);
}
return body as T;
}
/** One brand by slug, or null when the slug does not exist. Server-side only. */
export async function getBrand(slug: string, secretKey: string, fetchImpl: typeof fetch = fetch): Promise<Brand | null> {
try {
const { data } = await request<{ data: Brand }>(`/brands/${encodeURIComponent(slug)}`, secretKey, fetchImpl);
return data;
} catch (error) {
if (error instanceof MotomarksError && error.status === 404) return null;
throw error;
}
}
/** Search published brands by name. `limit` is capped at 100 by the API. Server-side only. */
export async function searchBrands(
query: string,
secretKey: string,
{ limit = 20, vehicleType }: { limit?: number; vehicleType?: "car" | "truck" | "motorcycle" } = {},
fetchImpl: typeof fetch = fetch,
): Promise<Brand[]> {
const params = new URLSearchParams({ q: query, limit: String(limit) });
if (vehicleType) params.set("vehicleType", vehicleType);
const { data } = await request<{ data: Brand[] }>(`/brands?${params}`, secretKey, fetchImpl);
return data;
}
Picks the CDN size from the rendered pixel size (2x for high-density screens) and swaps to the initial on error.
import { useState } from "react";
import { logoUrl, sizeFor, type LogoType } from "@/lib/motomarks";
interface BrandLogoProps {
slug: string;
name: string;
/** Publishable pk_ key, restricted to your domains in the dashboard. */
publicKey: string;
type?: LogoType;
/** Rendered width and height in CSS pixels. */
px?: number;
}
export function BrandLogo({ slug, name, publicKey, type = "badge", px = 32 }: BrandLogoProps) {
const [failed, setFailed] = useState(false);
if (failed) {
// Unknown slug, revoked key or offline: keep the layout and show the initial.
return (
<span role="img" aria-label={`${name} logo`} className="brand-logo-fallback" style={{ width: px, height: px }}>
{name.charAt(0)}
</span>
);
}
return (
<img
src={logoUrl(slug, publicKey, { type, size: sizeFor(px) })}
alt={`${name} logo`}
width={px}
height={px}
loading="lazy"
decoding="async"
onError={() => setFailed(true)}
/>
);
}
Renders a make list from data your server fetched with searchBrands.
import { BrandLogo } from "./BrandLogo";
// `makes` comes from your backend (searchBrands with the sk_ key), never
// from the browser: secret keys must not ship in client bundles.
export function MakeList({ makes, publicKey }: { makes: Array<{ slug: string; brandName: string }>; publicKey: string }) {
return (
<ul className="make-list">
{makes.map((make) => (
<li key={make.slug}>
<BrandLogo slug={make.slug} name={make.brandName} publicKey={publicKey} px={24} />
<span>{make.brandName}</span>
</li>
))}
</ul>
);
}
Then use it:
<BrandLogo slug="byd" name="BYD" publicKey={import.meta.env.VITE_MOTOMARKS_PUBLIC_KEY} px={32} />3. What the API returns
{
"data": {
"id": "a30746ba-3a56-4199-8cc9-af39bfdae8bb",
"slug": "byd",
"brandName": "BYD",
"companyName": "BYD Company Limited",
"country": "China",
"parentCompany": null,
"foundedYear": "1995",
"officialDomain": "https://www.byd.com",
"color": "#E60012",
"colors": [
"#E60012",
"#FFFFFF",
"#000000"
],
"vehicleTypes": [
"car"
],
"updatedAt": "2026-09-04T04:13:42.072Z"
}
}4. Handle every error
401 · Missing, malformed or revoked key
Fix configuration; do not retry.
{
"error": "Unauthorized",
"message": "API key required. Include 'Authorization: Bearer YOUR_API_KEY' header"
}403 · Plan inactive, Free plan without a verified attribution link, or a domain-restricted key used elsewhere
Branch on code: SUBSCRIPTION_REQUIRED or DOMAIN_NOT_ALLOWED.
{
"error": "Subscription Required",
"message": "Attribution link required. Add a link to https://motomarks.io on your site and verify it in your dashboard settings.",
"code": "SUBSCRIPTION_REQUIRED"
}404 · Slug is not a published brand
Return null and render your fallback.
{
"error": "Not Found",
"message": "Brand not found"
}429 · Free plan daily request limit reached
Serve cached data; retrying the same day will not succeed.
{
"error": "Rate Limit Exceeded",
"message": "Free plan is limited to 1,000 requests per day. Upgrade your plan for higher limits.",
"code": "RATE_LIMIT_EXCEEDED"
}5. Before you ship
- Keep sk_ keys on the server
- The JSON API takes the secret sk_ key. Call it from a server, route handler or build step, never from browser code. Image URLs use the publishable pk_ key, which is safe in HTML.
- Restrict the pk_ key to your domains
- Add your production and preview domains to the key in the dashboard. The CDN then refuses requests from other sites, and requests with no Origin or Referer fail closed.
- Cache brand data, not just images
- Brand records change rarely. Cache API responses for hours or a day and let the CDN cache images; each JSON call counts toward the daily request limit on the Free plan.
- Render a fallback for every logo
- A revoked key, an unknown slug or a network error should leave the layout intact. Every example falls back to the brand initial at the same size.
Ship React logos today.
Create a free key, paste it into the variables above, and the examples work as written.
Free includes 1,000 requests per day with an attribution link. Startup and Pro remove attribution.