Skip to Content
Takumi

Fonts

Load local or Google Fonts, choose fallbacks for multilingual text, and control variable axes and synthetic styles in Takumi.

Load a font for every script your text uses.

Takumi never reads system fonts. The only built-in font is Geist, which covers Latin at weights 300 to 800 and comes last in every fallback chain. Generic families such as sans-serif resolve to the fonts you load.

Loading fonts

The fonts option

Pass the fonts a render needs through fonts. Each entry takes one of three forms:

EntryResolves to
URL stringFetched on demand, keyed by the URL. 1
Raw bytesA Uint8Array, ArrayBuffer, or Buffer, registered directly.
Descriptor{ name, data, weight, style, generic, unicodeRange, cache, optional }. 2

1 Name, weight, and style come from the file. Takumi downloads it with the fetch, timeout, maxBytes, and allowUrl you pass in images, as it does images.

2 A descriptor's fields override what the file reports.

The native @takumi-rs/core reads WOFF2, WOFF, TTF, OTF, and TTC files. The WebAssembly packages read all of them except WOFF, so convert a WOFF font to WOFF2 for an edge runtime.

render, renderSvg, renderAnimation, measure, and ImageResponse all take fonts. It also takes a promise of the list, so pass googleFonts(...) without await. The renderer decodes each file once and keeps it until you release it, or until the renderer evicts it to make room. Among equally matching faces of one family that cover the character, the one listed last wins, as a later @font-face rule does.

Load a font URL
import {  } from "takumi-js/response";

export function () {
  return new (<>Hello Takumi</>, {
    : ["https://example.com/Inter.woff2"], 
  });
}

A descriptor's data is raw bytes or a function that returns them:

Override font metadata
import {  } from "takumi-js/response";

export function () {
  return new (<>Hello Takumi</>, {
    : [
      {
        : "Inter",
        : 700,
        : () => ("https://example.com/Inter.woff2").(() => .()),
      },
    ],
  });
}

Leave weight out for a variable font. The font then serves every weight along its wght axis, as an @font-face rule without font-weight does. A weight pins the font to that one weight, so registering one variable file once per weight only adds copies.

unicodeRange limits the font to inclusive [start, end] codepoint ranges, as @font-face unicode-range does. Register each subset of a family under the same name with its own ranges, and each character uses the subset that covers it.

generic assigns the font to a CSS generic family keyword. A stack that ends in monospace or serif then reaches the font without naming it. This is how Tailwind's font-mono finds it:

Assign a generic font family
import {  } from "takumi-js/response";

export function () {
  return new (< ="font-mono">let x = 1;</>, {
    : [
      {
        : "Geist Mono",
        : "monospace", 
        : () => ("https://example.com/GeistMono.woff2").(() => .()),
      },
    ],
  });
}

From Google Fonts

Load multilingual fonts
import {  } from "takumi-js";
import {  } from "takumi-js/helpers";

const  = await (< ={{ : "Inter" }}>Hello 你好 こんにちは</>, {
  : 1200,
  : 630,
  : (["Inter", "Noto Sans JP", "Noto Sans TC"]),
});

googleFonts makes one CSS request for all the families. Font files download only when the text needs them, as subsetting describes. Use the family name in fontFamily.

Pass an object instead of a name to set a family's weight, style, or variable axes:

Choose font weights and axes
import {  } from "takumi-js/helpers";

await ([
  {
    : "Inter",
    : [400, 700],
    : "italic",
  },
  {
    : "Noto Sans JP",
    : "600..700", // range loads the variable font
  },
  {
    : "Fraunces",
    : "100..900",
    : { : "9..144" }, // vary the optical-size axis too
  },
]);
FieldAcceptsEffect
namea family nameThe family to load. 1
weighta weight, an array, or a range "100..900"Which weights to fetch. 2
style"normal", "italic", or bothWhich styles to fetch. 3
axes{ tag: value | "min..max" }Variable axes to load, such as { opsz: "9..144" }. 4
generica CSS generic family keywordEvery loaded subset claims it, so font-mono can resolve to the family.

1 Known families autocomplete their weights and axes.

2 weight defaults to 400. A range loads the variable font, and font-weight drives it.

3 style defaults to "normal".

4 An axis given as a range stays variable.

Pass an object instead of an array for request options:

Limit font requests
import {  } from "takumi-js/helpers";

const  = await ({
  : ["Inter"],
  : 3000, 
});
OptionAcceptsEffect
familiesthe list aboveThe families to load, in fallback priority order.
displaya font-display valueSent as display in the CSS request.
texta stringLoads one file for each face, holding just these characters. 1
cacheMode"auto" or "none"Whether a renderer keeps the subsets. See Fonts used once.
cachea MapReplaces the download store for CSS responses.
baseUrla css2 endpointPoint at a mirror such as https://fonts.bunny.net/css2.

1 See Fonts for known text.

googleFonts also takes the fetch options: timeout, signal, maxBytes, allowUrl, and fetch. The timeout covers each request on its own, first the CSS request and then each font file. It does not cover the whole render.

Caching covers the store that keeps the CSS and font files.

Fonts for known text

When you know the text before you load the fonts, pass it as text. Google then answers with one file for each face that holds those characters, plus the ones shaping them needs:

Load only the title's characters
import {  } from "takumi-js";
import {  } from "takumi-js/helpers";

const  = "東京の夜景";

const  = await (< ={{ : "Noto Sans JP" }}>{}</>, {
  : 1200,
  : 630,
  : ({ : ["Noto Sans JP"], :  }), 
});

Different text loads a different file, and the same characters in any order load the same one. Past 6000 characters once URL-encoded, Google stops honoring text, so googleFonts leaves it out and loads the unicode-range subsets instead.

text costs a download for every new set of characters, while the subsets stop downloading once a renderer holds the ones your text uses. Choose by where the renderer runs:

  • On Workers and other short-lived isolates, or for a few titles that repeat, use text. A cold start downloads one small file, about 16 KB for a Japanese title, instead of every subset the text touches.
  • On a long-running server that renders varied text, leave text out. After the first renders, the subsets the renderer holds cover most new text.

Put all the text a render shows in one text. Splitting a run of Arabic, Devanagari, or another script that shapes its letters across two requests puts the letters in different files, and shaping breaks between them.

From @font-face rules

An @font-face rule in css or a <style> element loads its font as a browser does. render, ImageResponse, and each renderer's prepare() download the src files the text reaches, and skip the rest.

Load a font from CSS
import {  } from "takumi-js";

const  = await (< ={{ : "Brand" }}>Hello</>, {
  : 1200,
  : 630,
  : `
    @font-face {
      font-family: Brand;
      src: url("https://example.com/Brand.woff2") format("woff2");
    }
  `,
});

The rule's descriptors, such as font-weight, unicode-range, and size-adjust, apply as they do in Chrome. When a src fails to download, the rule moves on to its next source for that render, and the next prepare() tries the file again. A local() source names a font you loaded through fonts, by its full name or PostScript name. Takumi downloads the files with the fetch, timeout, maxBytes, and allowUrl you pass in images, so a relative URL needs your own fetch. The renderer keeps the files in its download store.

A renderer's render() called without prepare() downloads nothing. It draws with the @font-face files the renderer already holds, and falls back past the rest.

Fonts in CI and offline renders

Bundle font files when a render must work without Google Fonts:

Fonts in CI and offline renders
import {  } from "node:fs/promises";
import {  } from "takumi-js";

const  = await (new ("./fonts/Inter.woff2", import..));

const  = await (< ={{ : "Inter" }}>Hello</>, {
  : [{ : "Inter", :  }],
});

Retries recover a brief outage. They do not help when the host is down or the CI network blocks it. Run unit tests against local files or an injected fetch, and test the live service separately. An outer test or route timeout can end the render before the font timeout does. Set timeout below that outer limit, and leave time for layout and encoding.

CJK families can have many coverage subsets. Takumi downloads only the subsets your text uses, in the families and weights it is set in. A timeout during await googleFonts(...) comes from the CSS request, before any font file downloads.

Subsetting

render registers only the subsets the content draws. The same fonts list works for any text, and unused ranges never download. This runs on every render.

Font kindBehavior
Ranged subsets (from googleFonts)Kept only when font matching reaches them for a character, as a browser downloads a unicode-range face.
Whole files (URL string, raw bytes)No unicode-range, so they always load.

Takumi reads the text after styles apply, so generated content and text-transform count, and so does the text inside SVG images, such as chart labels. Each character goes through its own font stack. With font-family: Inter, "Noto Sans JP", Latin text loads only Inter's Latin subset, and a weight loads only when text uses it.

Before a subset downloads, font matching knows only the weight and style declared for it. A subset declared without them counts as normal, so a variable font's other weights only match it after it loads.

Reusing fonts across renders

render, renderSvg, renderAnimation, measure, and ImageResponse share one renderer per process. The first render that lists a font loads it, and later renders that list the same entry reuse it. Define the fonts list once and pass it to every render:

Share one fonts list
import {  } from "node:fs/promises";
import {  } from "takumi-js/response";

const  = [
  "https://example.com/Inter.woff2",
  { : "Brand", : await (new ("./fonts/Brand.woff2", import..)) },
];

export function () {
  return new (< ={{ : "Inter" }}>Hello Takumi</>, {
    : 1200,
    : 630,
    , 
  });
}

The renderer recognizes an entry it already holds by a key:

EntryKey
URL stringThe URL.
Raw bytesThe buffer object.
Descriptor with bytesThe buffer object and the descriptor's fields.
Descriptor with a data()Its name, weight, style, and unicodeRange.

A list defined at module level passes the same entries on every render, so the renderer finds each one by its key and loads nothing. A buffer read again inside the handler is a new key, so every render reads the file again and the renderer compares its bytes with the fonts it holds. A match reuses that decoded font, and the file decodes again only when no held font matches, such as after you release it.

A render's own fonts list reaches only that render, as a page sees only its own @font-face rules, so renders that list different fonts never change each other's output. Every render also draws with the fonts registerFont registered.

Releasing fonts

A renderer keeps every font it loads. On a renderer you create, release the ones you no longer need:

renderer.unregisterFont({ name: "Inter" }); // every face and subset of Inter
renderer.clearFonts(); // back to the built-in Geist

A later render that lists a released font loads it again. The renderer also evicts the fonts that renders' lists load when it needs room, one file at a time. To let each one go as soon as no render uses it, set cache.fonts to "none".

Fonts used once

A font in the fonts list takes a cache mode, as an image does, and googleFonts sets it on every subset from its cacheMode option. "none" lets the renderer drop a font it loaded for a render once that render settles, so a font that one render needs does not push out fonts that many renders share. A render still uses a font the renderer already holds, and leaves it there.

A subset that googleFonts loads for text drops the same way under the default "auto", since another render rarely asks for the same characters. Every other font under "auto" stays until the renderer needs the room:

Drop a font after its render
const  = await (< ={{ : "Noto Sans JP" }}>{}</>, {
  : 1200,
  : 630,
  : ({ : ["Noto Sans JP"], :  }), 
});

A font another render is using stays until the last of them settles. A render without "none" that uses the font keeps it. The downloaded file still goes to the download store, so the next render that needs it skips the download. Set the store to null to keep neither.

Fonts that may fail

A font in the fonts list takes optional: true. When it fails to download, allowUrl refuses its URL, or its bytes do not decode, the render goes on without it, as an @font-face rule moves on past a failed src. Text falls back to the next font in its stack. A font without optional still rejects the render.

A URL string cannot carry options, so pass fontFromUrl(url, { optional: true }) to mark a URL optional. That loader downloads with the fetch options you give fontFromUrl, not the ones in the render's images:

Render without a font that fails
import {  } from "takumi-js";
import {  } from "takumi-js/helpers";

const  = await (< ={{ : "Brand, Inter" }}>Hello</>, {
  : 1200,
  : 630,
  : [
    ("https://example.com/Inter.woff2"),
    ("https://cdn.example.com/Brand.woff2", { : true }), 
  ],
});

A descriptor takes the field directly, such as { name: "Brand", data: loadBrand, optional: true }.

A prepared source picks its unicodeRange subsets once, in prepare. When an optional font it picked loads there but fails when a later render loads it again, as after the renderer released it, that render draws without it and does not reach the next family for those characters. Prepare the source again to pick its subsets anew.

What a render could not draw

A render that cannot draw something as its source asks goes on without it and prints a warning through console.warn. Each warning starts with takumi: , as the warnings for unsupported CSS do. A render prints one for each of these:

  • The characters no font in their fallback chain draws, the built-in Geist included, in one warning per render.
  • Each family that font-family or fontFamilies names and no registered or listed font provides.
  • Each optional font or @font-face file that failed to load.
  • Each image left out under throwOnError: false.
takumi: No font draws "世界". Add a font that covers them to `fonts`, or return one from `loadFallbackFonts`.

Generic keywords such as sans-serif never count as unresolved, since they resolve to the fonts you load. Emoji that takumi-js draws as images never count as missing characters. Spaces and invisible characters, such as a zero-width joiner, do not count either.

Takumi prints every warning each time a render raises it, and has no option to silence them. A renderer's prepare() prints the warnings it finds, and a later render of the prepared source warns only about a font that fails when it loads again. To collect the warnings somewhere else, wrap console.warn, as Handle warnings shows.

A renderer's render() called without prepare() checks for missing characters and unresolved families only when the render passes loadFallbackFonts.

Takumi finds these warnings before layout, with the same font matching that draws the text. It checks one character at a time, so a character that shaping draws from a decomposed form, such as an accented letter built from a base letter and a combining mark, can still show up as missing.

Load fonts for missing characters

loadFallbackFonts loads fonts only for text that needs them. When the render finds characters no font draws, it calls the function once with those characters in document order. The fonts it returns load as part of the render's fonts, and the render reads the text again with them. Characters that stay uncovered still print the warning.

Load a CJK font only when the text needs it
const  = await (<>{}</>, {
  : 1200,
  : 630,
  : () =>
    ({ : ["Noto Sans JP"], : .("") }), 
});

Return undefined or an empty list to render without more fonts. The fonts the function returns follow the rules of the fonts list, so cache and optional apply to them too. When you pass fontFamilies, their families join the end of it, so the render falls back to them.

Choosing a font

Fallback chain

An element's own font-family comes first. When none of its families covers a character, Takumi tries fontFamilies in order, where a browser would try the system's fonts. So you don't need to append these families to every element's font-family. For an emoji, a color font anywhere in fontFamilies wins over an earlier font without color glyphs, as in Chromium.

Choose font fallback order
import {  } from "takumi-js";
import {  } from "takumi-js/helpers";

const  = await (<>Hello こんにちは</>, {
  : (["Inter", "Noto Sans JP"]),
  : ["Inter", "Noto Sans JP"], 
});

Without fontFamilies, the chain is the render's fonts in list order. A render without fonts uses every registered family in registration order. Geist always comes last.

A missing glyph walks the chain until a family covers it. googleFonts registers every subset under its family name with its unicode-range. Each character then uses the subset that covers it, as in a browser.

Variable axes & OpenType features

Set font axes with font-variation-settings and OpenType features with font-feature-settings. In a variable font, font-weight drives the wght axis and font-stretch drives wdth. Kerning is on by default, and font-kerning: none turns it off.

Set axes and OpenType features
<div
  style={{
    fontFamily: "Fraunces",
    fontVariationSettings: "'opsz' 72, 'wght' 700",
    fontFeatureSettings: "ss01",
  }}
>
  Variable Font Text
</div>

List a variable font once, as one entry with no weight. That entry serves every weight and keeps the font's axes live:

Load a variable font
import {  } from "takumi-js";

const  = await (
  < ={{ : "Fraunces", : 650 }}>Variable</>,
  {
    // a `weight` here pins the file to that instance instead
    : [
      {
        : "Fraunces",
        : () => ("https://example.com/Fraunces.woff2").(() => .()),
      },
    ],
  },
);

Do not list the same file once per weight. Each entry is its own key, so each one fetches the file again before the renderer matches its bytes to the font it already holds. googleFonts loads a variable font this way. A weight range or an axes entry fetches the variable file once and leaves its axes free.

Which axes a file exposes depends on the build. Google Fonts fixes the axes you did not request at their defaults, so Fraunces from there exposes only opsz and wght. Other builds keep SOFT and WONK live, and setting them changes the letterforms.

Synthetic bold & italic

When a family lacks the weight or style you asked for, Takumi draws a synthetic bold or oblique. font-synthesis controls this.

Synthetic bold & italic
<div style={{ fontFamily: "Inter", fontSynthesis: "none" }}>No faux bold</div>

List weight, style, small-caps, or any mix of them to allow each one. none turns them all off, so a missing bold weight draws at regular weight.

Typography covers styling text and controlling how it flows.

Last updated on