Skip to content

@hamur/fonts

The first-party fonts module. It finds the font families a stylesheet names, asks a font provider for their faces at build time and writes the @font-face rules into that stylesheet, so a page ships no font JavaScript and the browser asks no font host. Add it to modules and set its options under the fonts config key.

ts
// hamur.config.ts
import fonts from "@hamur/fonts"

export default defineConfig({
  modules: [fonts],
  fonts: { families: [{ name: "Brand", src: "#app/assets/fonts/Brand.woff2", weights: [600] }] },
})
css
/* app/main.css */
:root {
  font-family: Inter, sans-serif;
}

With public/Inter.woff2 the stylesheet is built with one rule added after its leading @charset, @import and @layer <names>; statements (CSS ignores an @import that follows a rule):

css
@font-face {
  font-family: "Inter";
  src: url(/Inter.woff2) format("woff2");
  font-display: swap;
}

default

The module, as defineModule({ meta: { name: "fonts", configKey: "fonts" } }). Its setup checks fonts (a wrong value is a build error naming the key), returns when fonts.enabled is false, and adds the transform fonts:css.

fonts:css runs in hamur build and hamur dev on every CSS module of the client build: a .css file, a .vue or .svelte style block after its compiler, and @hamur/css output. It is client only, because the server build empties CSS. A ?inline stylesheet is built by a child build with no plugins and is not seen.

  • What it reads. Every font-family declaration, the font shorthand (the list after the size and an optional / <line-height>; a font with no size is not read) and, by processCSSVariables, custom properties, at any depth of nesting. A comment, a string, a url() and an attribute selector are skipped. A declaration inside @font-face is a descriptor, not a use.
  • What it skips. Generic families (serif, sans-serif, monospace, cursive, fantasy, system-ui, ui-*, emoji, math, fangsong), CSS-wide keywords, var(), env() and attr(), and the system names -apple-system, BlinkMacSystemFont, Arial, Helvetica, Helvetica Neue, Times New Roman, Georgia, Courier New, Verdana, Tahoma, Trebuchet MS, Menlo, Monaco, Consolas, Segoe UI, Roboto, SF Pro, Noto Sans, Ubuntu, Cantarell, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji, SFMono-Regular, Liberation Mono, Courier, Cambria and Times (the fallback names of the Tailwind and UnoCSS font stacks); a system name is resolved only when fonts.families lists it. A family that an @font-face of the same file declares is not asked for; declare one from another file with families: [{ name, provider: "none" }].
  • What it writes. One @font-face per face of each family it resolves, each once per file. A face's src is the file's public URL, or the absolute path of the file, which the asset pipeline copies into the client output as <name>-<hash>.<ext> below app.buildAssetsDir (under app.cdnURL when set; a file of at most build.assetsInlineLimit bytes becomes a data: URI). A public/ file keeps its public URL when Bun's CSS bundler leaves a root-absolute url(/Inter.woff2) alone, which the module checks once per process; when Bun does not, it is written like an asset.
  • Files. Each remote src URL of a resolved face is downloaded once, and kept between builds, in <cacheDir>/fonts/files/<family>-<weight>-<style>-<subset>.<ext> and the @font-face points at that file, so the asset pipeline serves it as <name>-<hash>.<ext> below app.buildAssetsDir (under app.cdnURL when set, inlined up to build.assetsInlineLimit). A failed download is logged as [fonts] could not download <url>: <status> and the remote URL stays; with fonts.throwOnError it stops the build with the same text.
  • Warnings. A family no provider resolves is logged once per build, [fonts] no provider found for "Foo", and left to the browser; with fonts.throwOnError it stops the build with the same text. A failing provider is logged as [fonts] <provider> failed for "Foo": <message> and the next of priority is asked.
  • Hooks. meta.hooks declares fonts:providers and fonts:resolved, typed in HamurHooks. fonts:providers(providers: Record<string, FontProvider>) runs once in modules:done, after the files of fonts.providers are loaded, with every built-in and custom provider by name: a module or hooks in the config adds one or replaces one by assigning its key. fonts.priority is checked after it, so a name added there may be listed (an unknown name is fonts.priority[0] "bing" is not a provider (…) as before). fonts:resolved({ family, faces, files }) runs once per family, after its files are downloaded and subset: faces are the faces as written into the CSS and files the absolute paths of those that are files on disk.
  • hamur dev. The same transform. A family is resolved once per process, so a font file added to public/ or assets/fonts/ while the server runs is found after a restart.

FontsOptions

KeyTypeDefault
enabledbooleantrue: false adds no transform. fonts: false never reaches the module, since a false section is skipped by the config merge; per mode, $development: { fonts: { enabled: false } }
prioritystring[]["local", "npm", "google", "bunny", "fontshare", "fontsource", "googleicons", "adobe"]: the order in which providers are asked; a name is a built-in or a key of providers. A name without a provider is skipped
providersRecord<string, false | string | { options? }>{}: false removes a built-in, a string is the file of a custom provider (from the app root; a package.json imports key works) that default-exports a FontProvider, { options } sets a built-in's options
defaultsPartial<FontDefaults>see FontDefaults
familiesFontFamilyOptions[][]: per-family options; a listed family is always resolved
processCSSVariablesboolean | "font-prefixed-only""font-prefixed-only": --font-*: Inter, sans-serif is read; true reads every custom property, false none
fallbacksfalse | Record<string, string[]>{ "sans-serif": ["Arial"], serif: ["Times New Roman"], monospace: ["Courier New"] }: the system fonts a fallback face imitates, one face per name, for the generic family the declaration ends with (a list that ends with none takes sans-serif); false writes no fallback face. See Fonts
localSourcesbooleantrue: a provider's local("<name>") sources stay in each src; false drops them (a face left with no file is dropped), so no installed copy of the font is used. The local("Arial") of a fallback face stays
cachebooleantrue: provider answers and font files are kept in <cacheDir>/fonts/{meta,files} and never expire (rm -r renews); false downloads each build into <buildDir>/fonts
throwOnErrorbooleanfalse: every [fonts] warning stops the build with the same text; all of them go through one function

The load errors name the key: fonts.enabled must be a boolean (got "yes"), fonts.priority[0] "bing" is not a provider (local, npm, google, bunny, fontshare, fontsource, googleicons, adobe, or a key of fonts.providers), fonts.providers.mine "./x.ts" does not exist, fonts.providers.mine "./x.ts" must default-export { name, resolveFont } (got undefined), fonts.providers.mine "./x.ts" exports name "other"; the key and the name must match, fonts.providers.adobe.options.id is required (the Adobe Fonts kit id), fonts.defaults.weights[0] must be a CSS weight, 1 to 1000, or a range such as "100 900" (got 0), fonts.families[1] "Inter" is listed twice; merge the entries, fonts.families[0].src "./a.woff2" does not exist, fonts.families[0] sets src and provider; src means no provider is asked, fonts.families[0].weights lists 2 weights for 1 src file; list one weight per file, fonts.families[0].colour is not an option; use name, provider, src, weights, styles, subsets, display, formats, preload, unicodeRange, stretch, featureSettings, variationSettings, glyphs, global and fonts.speed is not an option; use enabled, priority, providers, defaults, families, processCSSVariables, fallbacks, localSources, cache, throwOnError. fonts.defaults.<key> is not an option names the keys of FontDefaults the same way.

FontDefaults

KeyTypeDefault
weightsArray<number | "400" | "100 900">[400]: "100 900" is a variable range
stylesArray<"normal" | "italic" | "oblique">["normal"]
subsetsstring[]["latin", "latin-ext"]
display"auto" | "block" | "swap" | "fallback" | "optional""swap": the font-display of each rule
formatsFontFormat[]["woff2"]
preloadbooleantrue

FontFamilyOptions

name plus every key of FontDefaults, and provider (a provider name, or "none": the app declares this family's faces itself), src (a font file or a list of them, a package.json imports key allowed: no provider is asked, and the n-th of weights and styles is the n-th file's), unicodeRange, stretch, featureSettings, variationSettings (each written into every rule of the family), glyphs and global. glyphs adds &text=<glyphs> (each character once, URL-encoded) to the google and googleicons requests, so the provider returns a subset whose file name carries a short hash of the glyphs; for any other provider, a src file or a local file Hamur cuts the TrueType file itself to those characters and their composite parts and writes it as WOFF2 (name, OS/2, the hinting tables and the pairs of a format 0 kern table are kept, GPOS kerning is not). A CFF font logs [fonts] Foo is CFF; glyphs applies to TrueType outlines only and a variable font with gvar logs [fonts] Foo is a variable font with gvar; glyphs does not subset it; both are kept whole, as is a WOFF2 whose glyf table is transformed. global: true writes the family's faces into the global CSS (#hamur/fonts/global.css, imported by an app plugin), linked on every page and in dev, even when no CSS names the family. preload: true (the default) lists the file of the family's latin face (else the first of subsets) in the <link rel="preload"> lines the server writes before a document's first stylesheet. See Fonts.

FontProvider

{ name: string; resolveFont(family, options): Promise<FontResolution | undefined> }. A custom provider is a file that default-exports one (export default { name: "mine", resolveFont } satisfies FontProvider); there is no defineFontProvider. It returns undefined when it does not have the family; an error it throws is logged and the next provider is asked.

The built-in local provider reads <srcDir>/assets/fonts/** of the app and its layers, then their public/ directories: a file <Family>-<weight>[-<style>].{woff2,woff,ttf,otf} or <Family>.<ext>, the family compared without case, spaces and hyphens, a weight a number or thin to black, a style italic or oblique. Files of one weight and style are one face, woff2 first. It returns every face it finds, whatever weights and styles say.

The other built-ins are written with fetch and ask at build and in hamur dev only. Each returns undefined when the service has no such family and throws on any other failure.

NameAsksNotes
npmthe app's installed @fontsource/<id> and @fontsource-variable/<id>, found in node_modules from the app root upward<id> is the family lower-cased with - for spaces; the files are the package's own, written as absolute paths. A weight range takes the variable package when it is installed, a single weight the static one
googlefonts.googleapis.com/css2?family=<Family>:wght@…&display=swap, with a Chrome user-agent so the files are woff2one face per subset; an answer of 400 or 404 is "no such family"
googleiconsthe same API for Material Symbols Outlined, Rounded, Sharp and Material Iconsthe default instance of the icon font
bunnyfonts.bunny.net/css?family=<family>:<weights>static weights: a range asks every hundred inside it
fontshareapi.fontshare.com/v2/css?f[]=<slug>@<weights>, weights joined with ;, i after an italic weight, a range as 300..900
fontsourceapi.fontsource.org/v1/fonts/<id>static weights: a range takes the weights inside it
adobeuse.typekit.net/<id>.css, the kit id in fonts.providers.adobe.options.idwith no id it has no answer; it returns the kit's faces of the family, whatever weights says

ResolveFontOptions

What a provider is asked: weights (strings: "400", "100 900"), styles, subsets, formats, glyphs, the provider's options from fonts.providers.<name>.options, and fetch, the build's fetch.

FontResolution

{ fonts: FontFaceData[]; fallbacks?: string[] }.

FontFaceData

One face: src ({ url, format? } or { name } for local("name")), and the descriptors weight, style, stretch, unicodeRange, display, featureSettings, variationSettings and subset. A descriptor a family sets in FontFamilyOptions is written instead of the provider's; the face's display wins over the default.

FontFormat

"woff2" | "woff" | "ttf" | "otf", written as format("woff2"), format("woff"), format("truetype") and format("opentype").

@hamur/fonts/providers

remoteProviders

Record<string, FontProvider>: the built-in providers that ask a font host (google, googleicons, bunny, fontshare, fontsource, adobe), by name. Code that needs a family's files outside a stylesheet asks one directly, as @hamur/og-image does for ogImage.fonts; the module's cache and priority are not applied.

createNpmProvider

createNpmProvider({ rootDir }): FontProvider: the npm provider, which reads @fontsource packages installed below rootDir.

@hamur/fonts/server

Server code only: the file starts with import "hamur/server-only", so a page or any client code that imports it fails the build with the import guard's is server-only … and cannot be imported from client code.

getFontData

ts
function getFontData(family: FontFamilyName): Array<{ src: string; weight: string; style: string; format: string }>

The self-hosted files of a family the build resolved, one entry per url of each face. src is the URL the built CSS holds (/_hamur/Inter-400-a1b2c3d4.woff2, with app.cdnURL in front when it is set); in hamur dev it is the absolute path of the file under <cacheDir>/fonts/files, and a family is listed once a stylesheet that names it has been requested. A face whose file the asset pipeline inlined as a data: URL has no entry. An unknown name throws fonts: "Inter" is not a resolved family (Inter Tight, Fira Code), the resolved names listed ((none) when there are none). family is typed with the names of the last build: .hamur/types/fonts.d.ts adds each to HamurFontFamilies, and until a build has written them the parameter is a string.

ts
// server/og.ts
import { getFontData } from "@hamur/fonts/server"

const [regular] = getFontData("Inter")

fonts

Record<string, Array<{ src: string; weight: string; style: string; format: string }>>: every resolved family, by name, with the entries getFontData returns.

FontData, FontFamilyName, HamurFontFamilies

Types: one entry of the lists above, the name getFontData takes, and the interface the generated types file fills with one true key per family.

Icon fonts

The googleicons provider answers Material Symbols Outlined, Rounded, Sharp and Material Icons. With { name: "Material Symbols Outlined", provider: "googleicons", glyphs: "home search" } it asks text=home%20sarc (each character once), downloads the one subset file and writes its face into any stylesheet with font-family: "Material Symbols Outlined".