# Fonts

`@hamur/fonts` finds the font families your CSS names, asks a font provider for their files at build time, writes the `@font-face` rules into your stylesheet and serves the files from your own origin. A page ships no font JavaScript, and the browser asks no font host. The module also adds fallback faces, so the text does not jump while a font loads, and preload links for the files a page uses.

```sh
bun add @hamur/fonts
```

````ts [fonts/config.ts]
import { defineConfig } from "hamur"
import fonts from "@hamur/fonts"

export default defineConfig({
  framework: "react",
  modules: [fonts],
  fonts: {
    defaults: { weights: [400, 700], subsets: ["latin"] },
    families: [
      { name: "Inter", weights: ["100 900"], preload: true },
      { name: "Fira Code", provider: "bunny", weights: [400] },
      { name: "Brand", src: "#app/assets/fonts/Brand.woff2", weights: [600] },
    ],
  },
})
````

Add the module to `modules`; its options live under the `fonts` key. Write the families in your CSS as you always do:

````css [fonts/main.css]
:root {
  font-family: Inter, sans-serif;
}

code {
  font:
    14px/1.5 "Fira Code",
    monospace;
}

h1 {
  font-family: Brand, sans-serif;
}
````

`Inter` has no file in your app, so the build asks the providers in order until one has it. `Brand` has a `src`, so no provider is asked. The generic families and the system fonts (`sans-serif`, `Arial`, `Segoe UI` and the like) are never fetched. Every option is in the [reference](/api-reference/fonts#fontsoptions).

## What the build reads

The module runs on the CSS the client build compiles: a `.css` file, a `.vue` or `.svelte` style block, Sass, Less and Stylus output, [`@hamur/css`](/styling) output, Tailwind's compiled CSS and every stylesheet the app imports. It reads `font-family`, the `font` shorthand and, by `processCSSVariables`, custom properties such as `--font-sans: Inter, sans-serif`. A declaration inside `@font-face` is a face you wrote, not a use. A family that an `@font-face` of the same file declares is left alone; declare one from another file with `{ name, provider: "none" }`.

It never runs a component, so a family that only JavaScript names is not found. The table [When a font is not picked up](#when-a-font-is-not-picked-up) says what to do.

## Providers

A provider answers "what faces does this family have?" For each family the module asks `families[].src` first (no provider), then `families[].provider` (only that one), then each provider of `priority` in order. The first answer wins. A provider that throws is logged and the next is asked.

| Name          | Where the files come from                                                                                                                |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `local`       | `app/assets/fonts/` of the app and its layers, then their `public/`: a file `Inter-700.woff2`, `Inter-700-italic.woff2` or `Inter.woff2` |
| `npm`         | `@fontsource/<id>` and `@fontsource-variable/<id>` packages the app installed                                                            |
| `google`      | Google Fonts, asked with a Chrome user agent so the files are woff2                                                                      |
| `bunny`       | Bunny Fonts                                                                                                                              |
| `fontshare`   | Fontshare                                                                                                                                |
| `fontsource`  | the Fontsource API                                                                                                                       |
| `googleicons` | Material Symbols (`Outlined`, `Rounded`, `Sharp`) and Material Icons from Google                                                         |
| `adobe`       | an Adobe Fonts kit; active only when `providers.adobe.options.id` is set                                                                 |

`priority` defaults to the order of this table. `providers.<name>: false` removes a built-in, `providers.<name>: { options }` sets its options, and `providers.<name>: "<file>"` adds your own. A custom provider is a file that default-exports a `FontProvider`; there is no `defineFontProvider`.

````ts [fonts/providers-config.ts]
import { defineConfig } from "hamur"
import fonts from "@hamur/fonts"

export default defineConfig({
  framework: "react",
  modules: [fonts],
  fonts: {
    priority: ["local", "npm", "bunny", "google", "adobe"],
    providers: {
      fontshare: false,
      adobe: { options: { id: "abc1def" } },
      "brand-cdn": "./app/fonts/brand-cdn.ts",
    },
    families: [{ name: "Brand Sans", provider: "brand-cdn", weights: [400, 700] }],
  },
})
````

````ts [fonts/brand-cdn.ts]
import type { FontProvider } from "@hamur/fonts"

export default {
  name: "brand-cdn",
  async resolveFont(family, options) {
    if (family !== "Brand Sans") return undefined
    return {
      fonts: options.weights.map((weight) => ({
        src: [{ url: `https://fonts.example.com/brand-sans-${weight}.woff2`, format: "woff2" }],
        weight,
        style: "normal",
      })),
    }
  },
} satisfies FontProvider
````

`resolveFont` returns the faces of the family, or `undefined` when it does not have it. The `fonts:providers` hook adds or replaces a provider from a module instead, and `fonts:resolved` runs once per family with its faces and files.

The remote providers ask at build time and in `hamur dev` only. Nothing in the built HTML or CSS names `fonts.googleapis.com`, `fonts.gstatic.com` or `fonts.bunny.net`, unless a download failed and the remote URL was kept.

## Self-hosted files

Each remote file is downloaded once and written to `<cacheDir>/fonts/files/<family>-<weight>-<style>-<subset>.<ext>`. The `@font-face` points at that file, and the asset pipeline copies it into the client output as `<name>-<hash>.<ext>` below `app.buildAssetsDir`. The static server sends it `immutable`. A file of at most `build.assetsInlineLimit` bytes (4096) becomes a `data:` URI; a glyph subset of an icon font may be that small.

A file in `public/` keeps its public URL when Bun's CSS bundler leaves a root-absolute `url()` alone, and is hashed like an asset when it does not.

**With a CDN.** Under `app.cdnURL` the font URLs point at the CDN, and a browser asks for a font with an anonymous CORS request, even from the same site. The CDN must answer font files with `access-control-allow-origin` for your site (`*` is enough for public fonts). Without it neither the preload nor the face loads, and the text stays in its fallback. See [Build output](/build-output) for `app.cdnURL`.

## The cache and CI

Provider answers and files are kept in `<cacheDir>/fonts` (`node_modules/.cache/hamur/fonts` by default). They never expire, as a lockfile does not: a second build makes no request and writes the same CSS and files. `rm -r <cacheDir>/fonts` renews them; `hamur build --force` does not touch them.

With no cached copy and no network, the build stops with `[fonts] cannot reach fonts.googleapis.com and no cached copy of "Inter" exists`. In CI the cache directory is empty on a fresh runner, so keep it between runs:

````yml [fonts/ci-cache.yml]
- uses: actions/cache@v4
  with:
    path: node_modules/.cache/hamur/fonts
    key: hamur-fonts-${{ hashFiles('hamur.config.ts') }}
    restore-keys: hamur-fonts-
- run: bun run build
````

`fonts.cache: false` reads and writes nothing under `<cacheDir>/fonts`; each build downloads its files into `<buildDir>/fonts`.

## Fallback faces

For each web family the module writes a fallback face that imitates a system font, with `size-adjust` and `ascent-override`, `descent-override` and `line-gap-override` computed from the font's own tables:

```css
@font-face {
  font-family: "Inter Fallback: Arial";
  src: local("Arial");
  size-adjust: 107.4%;
  ascent-override: 90.2%;
  descent-override: 22.5%;
  line-gap-override: 0%;
}
```

and adds it after the family in each declaration it rewrote: `font-family: Inter, "Inter Fallback: Arial", sans-serif`. The system font comes from the generic family the declaration ends with and `fonts.fallbacks` (`sans-serif` is `Arial`, `serif` is `Times New Roman`, `monospace` is `Courier New`). A list such as `["Arial", "Segoe UI"]` writes one face per name, so a machine without the first takes the next. `fallbacks: false` writes none.

A font whose file has no readable `cmap` gets no fallback face and logs `[fonts] no fallback metrics for "Foo": its file has no readable cmap`.

## Preload

A document's CSS names the font files it uses, so its preload lines come from its CSS. A server plugin writes `<link rel="preload" as="font" type="font/woff2" href="…" crossorigin>` before the first stylesheet, for the files of the families with `preload: true` (the default). Of the faces of one family only the `latin` subset (else the first of `subsets`) is listed. A family used only on `/about` has no preload line on `/`, and a client navigation adds none. `hamur dev` writes none. `preload: false` on a family or in `defaults` turns it off.

## Subsetting with `glyphs`

`glyphs: "home search menu"` keeps only those characters, which is how an icon font or a short heading face shrinks from hundreds of kilobytes to a few. Two cases:

- **`google` and `googleicons`** add `&text=…` to the request, so Google returns a subset file.
- **Any other file** (`local`, `npm`, a `src` file, a download from another provider) is cut by a TrueType subsetter that Hamur ships. It keeps the `cmap`, `glyf`, `loca` and `hmtx` entries of the characters and of the composite parts they use, and writes WOFF2. No tool is installed or run.

The subsetter reads TrueType outlines. A CFF (`.otf`) font is kept whole and logs `[fonts] Foo is CFF; glyphs applies to TrueType outlines only`; a variable font with a `gvar` table is kept whole and logs `[fonts] Foo is a variable font with gvar; glyphs does not subset it`. A WOFF2 whose `glyf` table is transformed (what Bunny, Fontsource and `@fontsource/*` serve) is kept whole with no line; give the family a `.ttf` next to it to cut that. Kerning in a `GPOS` table is not kept, so a subset draws each glyph as the full font does but does not kern; a `kern` table is kept.

````ts [fonts/options-config.ts]
import { defineConfig } from "hamur"
import fonts from "@hamur/fonts"

export default defineConfig({
  framework: "react",
  modules: [fonts],
  fonts: {
    processCSSVariables: true,
    fallbacks: { "sans-serif": ["Arial", "Segoe UI"] },
    families: [
      { name: "Inter", global: true },
      { name: "Material Symbols Outlined", provider: "googleicons", glyphs: "home search menu" },
      { name: "Brand", src: "#app/assets/fonts/Brand.ttf", glyphs: "Hamur 0123456789" },
    ],
  },
  $development: { fonts: { enabled: false } },
})
````

## Font data in server code

A route that draws an Open Graph image needs the font file's URL. `@hamur/fonts/server` has `getFontData(family)` and `fonts`, the self-hosted `{ src, weight, style, format }` entries of every family the build resolved:

````ts [fonts/og-font.ts]
import { getFontData } from "@hamur/fonts/server"
import { defineHandler } from "hamur/server"

export const ogFont = defineHandler({
  route: "/api/og-font",
  method: "GET",
  raw: true,
  handler() {
    const [regular] = getFontData("Inter")
    return { src: regular?.src, weight: regular?.weight }
  },
})
````

The file starts with `import "hamur/server-only"`, so importing it in client code fails the build. `getFontData("Nope")` throws `fonts: "Nope" is not a resolved family (Inter, Fira Code)`. The names are typed from the last build once `.hamur/types/fonts.d.ts` is written. In `hamur dev` the `src` is the absolute path of the cached file.

## Options

| Key                   | Default                                                                                                                       | What                                                                                                                                                                                                                                      |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled`             | `true`                                                                                                                        | `false` skips the module; per mode, `$development: { fonts: { enabled: false } }` (`fonts: false` is skipped by the config merge and never reaches the module)                                                                            |
| `priority`            | `["local", "npm", "google", "bunny", "fontshare", "fontsource", "googleicons", "adobe"]`                                      | the order providers are asked                                                                                                                                                                                                             |
| `providers`           | `{}`                                                                                                                          | `false`, a file path or `{ options }` per provider                                                                                                                                                                                        |
| `defaults`            | `{ weights: [400], styles: ["normal"], subsets: ["latin", "latin-ext"], display: "swap", formats: ["woff2"], preload: true }` | what a family gets when it says nothing; each style doubles the files in a build, so italic is opt-in                                                                                                                                     |
| `families`            | `[]`                                                                                                                          | per-family options: `name`, `provider`, `src`, `weights`, `styles`, `subsets`, `display`, `formats`, `preload`, `unicodeRange`, `stretch`, `featureSettings`, `variationSettings`, `glyphs`, `global`; a listed family is always resolved |
| `processCSSVariables` | `"font-prefixed-only"`                                                                                                        | which custom properties are read: `--font-*` only, every one (`true`) or none (`false`)                                                                                                                                                   |
| `fallbacks`           | `{ "sans-serif": ["Arial"], serif: ["Times New Roman"], monospace: ["Courier New"] }`                                         | the system fonts a fallback face imitates; `false` writes none                                                                                                                                                                            |
| `localSources`        | `true`                                                                                                                        | adds `local("<name>")` before the file in each `src`, so an installed copy is used                                                                                                                                                        |
| `cache`               | `true`                                                                                                                        | keep answers and files in `<cacheDir>/fonts`                                                                                                                                                                                              |
| `throwOnError`        | `false`                                                                                                                       | every `[fonts]` warning below stops the build with the same text                                                                                                                                                                          |

A wrong value fails the build with a message that names the key, for example `fonts.defaults.display "soon" is not a font-display value (auto, block, swap, fallback, optional)`; the full list is in the [reference](/api-reference/fonts#fontsoptions).

## When a font is not picked up

| What you see                                                                                                            | Why                                                                                           | Fix                                                                                                     |
| ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| The font is named only in JavaScript: `style={{ fontFamily: "Inter" }}`, a canvas `ctx.font`, a chart library's options | the build never runs a component and reads CSS only                                           | list it in `fonts.families` with `global: true`; its faces go into the global CSS, linked on every page |
| The family is in a custom property such as `--brand-font: Inter`                                                        | `processCSSVariables` reads `--font-*` only by default                                        | rename it `--font-brand`, set `processCSSVariables: true`, or list the family in `fonts.families`       |
| `[fonts] no provider found for "Inter"` and the provider is on your list                                                | the provider is set to `false` in `providers`, or missing from `priority`                     | remove the `false` or add the name to `priority`                                                        |
| `[fonts] no provider found for "Intr"`                                                                                  | the family name is misspelt, so no provider has it                                            | fix the name; the log line prints it as written                                                         |
| The family is `Arial`, `Roboto`, `Segoe UI` or another system name                                                      | system names are skipped unless you list them                                                 | list it in `fonts.families`                                                                             |
| The family is declared with `@font-face` in another CSS file                                                            | the scan sees one file at a time                                                              | in this file's config add `{ name: "Brand", provider: "none" }`                                         |
| A stylesheet imported with `?inline`                                                                                    | it is built by a child build with no plugins                                                  | import it normally, or name its families in `fonts.families` with `global: true`                        |
| CSS in `public/`, or a `<style>` in `app/documents/*.html`                                                              | those files are copied as they are and are not CSS modules of the build                       | move the rules into a CSS file the app imports                                                          |
| Tailwind v4: `--font-sans` is missing                                                                                   | Tailwind writes only the theme variables a used utility reads                                 | use the utility (`font-sans`) in a file Tailwind scans, or list the family in `fonts.families`          |
| UnoCSS or another generator: no family found                                                                            | the module reads the CSS the generator wrote; a family appears only when a used rule emits it | check the generated CSS has the `font-family`; otherwise list the family in `fonts.families`            |
| A font file you added to `public/` or `app/assets/fonts/` is not found in `hamur dev`                                   | a family is resolved once per process                                                         | restart `hamur dev`                                                                                     |

Tailwind v4 is read from its compiled CSS, where `@theme { --font-sans: Inter, sans-serif }` is a declaration, so the module needs no setup of its own for Tailwind:

````css [fonts/tailwind.css]
@import "tailwindcss";

@theme {
  --font-sans: Inter, sans-serif;
  --font-mono: "Fira Code", monospace;
}
````

## Warnings

Each is logged once per build under `[fonts]`; `throwOnError` makes each an error.

| Message                                                                | Cause                                                                                |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `[fonts] no provider found for "Foo"`                                  | no provider of `priority` had the family; it is left to the browser                  |
| `[fonts] <provider> failed for "Foo": <message>`                       | a provider threw; the next was asked                                                 |
| `[fonts] could not download <url>: <status>`                           | a font file answered a non-2xx status or no answer; the remote URL is kept           |
| `[fonts] cannot reach <host> and no cached copy of "Inter" exists`     | no cached answer and no network; this one stops the build whatever `throwOnError` is |
| `[fonts] no fallback metrics for "Foo": its file has no readable cmap` | no fallback face for it                                                              |
| `[fonts] Foo is CFF; glyphs applies to TrueType outlines only`         | `glyphs` on an `.otf` file                                                           |
| `[fonts] Foo is a variable font with gvar; glyphs does not subset it`  | `glyphs` on a variable TrueType font                                                 |

## Not in v1

A list of every family a provider has, subsetting CFF fonts, reading weights and styles from the `font-weight` and `font-style` declarations, resolving a font at run time, and a `font-display` or `unicode-range` split per route.
