Skip to content

🎥 Make videos programmatically with React

Add variable Google Font loading

JonnyBurger7553231c14c0
diff --git a/packages/docs/docs/google-fonts/load-variable-font.mdx b/packages/docs/docs/google-fonts/load-variable-font.mdx
new file mode 100644
index 0000000000..cad84c582f
--- /dev/null
+++ b/packages/docs/docs/google-fonts/load-variable-font.mdx
@@ -0,0 +1,89 @@
+---
+image: /generated/articles-docs-google-fonts-load-variable-font.png
+title: loadVariableFont()
+crumb: '@remotion/google-fonts'
+---
+
+# loadVariableFont()<AvailableFrom v="4.0.524" />
+
+_Part of the [`@remotion/google-fonts`](/docs/google-fonts) package_
+
+Loads a Google Font as a variable font. One font file can provide a continuous range of weights and other variation axes.
+
+This export is only available for fonts that Google Fonts provides as variable fonts.
+
+## Usage
+
+```tsx twoslash title="VariableFont.tsx"
+import {loadVariableFont} from '@remotion/google-fonts/NotoSans';
+import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';
+
+const {axes, fontFamily} = loadVariableFont('normal', {
+ subsets: ['latin'],
+});
+
+export const VariableFont: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill
+ style={{
+ fontFamily,
+ fontWeight: interpolate(frame, [0, 90], [
+ axes.wght.min,
+ axes.wght.max,
+ ]),
+ }}
+ >
+ Variable font
+ </AbsoluteFill>
+ );
+};
+```
+
+Prefer CSS properties such as `fontWeight` and `fontStretch` for registered axes. Use `fontVariationSettings` for custom axes.
+
+Variable fonts combine variation axes, but Google may still provide separate files for styles and character subsets.
+
+## Arguments
+
+### style
+
+The style to load, such as `normal` or `italic`.
+
+### options
+
+#### subsets
+
+The character subsets to load. At least one subset is required.
+
+#### document?
+
+The document into which the font should be added. By default, the global `window.document` is used.
+
+#### ignoreTooManyRequestsWarning?
+
+Set this to `true` to disable the warning emitted when loading more than 20 subset files.
+
+## Return value
+
+### fontFamily
+
+The font family name, for use with the `fontFamily` CSS property.
+
+### axes
+
+The minimum and maximum value of each available variation axis.
+
+### waitUntilDone()
+
+Returns a promise that resolves once the font files have loaded.
+
+## Compatibility
+
+<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio hideServers />
+
+## See also
+
+- [`loadFont()`](/docs/google-fonts/load-font)
+- [`@remotion/google-fonts`](/docs/google-fonts)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 0873626ab5..976a94016e 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -393,6 +393,7 @@ const sidebars: SidebarsConfig = {
},
items: [
'google-fonts/load-font',
+ 'google-fonts/load-variable-font',
'google-fonts/get-available-fonts',
'google-fonts/get-info',
'google-fonts/load-font-from-info',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 5b7755fff2..c0ffd3e5fc 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -2834,6 +2834,15 @@ export const articles = [
noAi: false,
slug: 'google-fonts/load-font',
},
+ {
+ id: 'google-fonts/load-variable-font',
+ title: 'loadVariableFont()',
+ relativePath: 'docs/google-fonts/load-variable-font.mdx',
+ compId: 'articles-docs-google-fonts-load-variable-font',
+ crumb: '@remotion/google-fonts',
+ noAi: false,
+ slug: 'google-fonts/load-variable-font',
+ },
{
id: 'gpu',
title: 'Using the GPU',
diff --git a/packages/docs/static/generated/articles-docs-google-fonts-load-variable-font.png b/packages/docs/static/generated/articles-docs-google-fonts-load-variable-font.png
new file mode 100644
index 0000000000..530d5043ff
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-google-fonts-load-variable-font.png differ
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsx
index cec2740f30..1b5004db46 100644
--- a/packages/example/src/Root.tsx
+++ b/packages/example/src/Root.tsx
@@ -182,6 +182,7 @@ import {
PUSH_CUT_DEMO_DURATION_IN_FRAMES,
PushCutDemo,
} from './Transitions/PushCutDemo';
+import {VariableGoogleFont} from './VariableGoogleFont/VariableGoogleFont';
import {VideoOnCanvas} from './VideoOnCanvas';
import {Greenscreen} from './VideoOnCanvas/greenscreen';
import {VideoParser} from './VideoParser';
@@ -3158,6 +3159,14 @@ export const Index: React.FC = () => {
fps={30}
durationInFrames={2 * 60 * 30}
/>
+ <Composition
+ id="variable-google-font"
+ component={VariableGoogleFont}
+ width={1280}
+ height={720}
+ fps={30}
+ durationInFrames={180}
+ />
</>
);
};
diff --git a/packages/example/src/VariableGoogleFont/VariableGoogleFont.tsx b/packages/example/src/VariableGoogleFont/VariableGoogleFont.tsx
new file mode 100644
index 0000000000..e7f355b69e
--- /dev/null
+++ b/packages/example/src/VariableGoogleFont/VariableGoogleFont.tsx
@@ -0,0 +1,62 @@
+import {loadVariableFont} from '@remotion/google-fonts/NotoSans';
+import React from 'react';
+import {
+ AbsoluteFill,
+ Easing,
+ interpolate,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+
+const {axes, fontFamily} = loadVariableFont('normal', {
+ subsets: ['latin'],
+});
+
+export const VariableGoogleFont: React.FC = () => {
+ const frame = useCurrentFrame();
+ const {durationInFrames} = useVideoConfig();
+ const weight = Math.round(
+ interpolate(
+ frame,
+ [0, (durationInFrames - 1) / 2, durationInFrames - 1],
+ [axes.wght.min, axes.wght.max, axes.wght.min],
+ {
+ easing: Easing.inOut(Easing.ease),
+ },
+ ),
+ );
+
+ return (
+ <AbsoluteFill
+ style={{
+ alignItems: 'center',
+ backgroundColor: '#f4f1e8',
+ color: '#161616',
+ justifyContent: 'center',
+ }}
+ >
+ <div
+ style={{
+ fontFamily,
+ fontSize: 150,
+ fontWeight: weight,
+ letterSpacing: -7,
+ lineHeight: 1,
+ }}
+ >
+ Variable
+ </div>
+ <div
+ style={{
+ fontFamily,
+ fontSize: 28,
+ fontWeight: 500,
+ letterSpacing: 4,
+ marginTop: 56,
+ }}
+ >
+ FONT WEIGHT {weight}
+ </div>
+ </AbsoluteFill>
+ );
+};
diff --git a/packages/google-fonts/scripts/extract-info-from-css.ts b/packages/google-fonts/scripts/extract-info-from-css.ts
index 675deabce0..c3c2e92d59 100644
--- a/packages/google-fonts/scripts/extract-info-from-css.ts
+++ b/packages/google-fonts/scripts/extract-info-from-css.ts
@@ -32,6 +32,10 @@ const parseFontFace = (block: string) => {
const style = getValue(
lines.find((line) => line.trim().startsWith('font-style')) as string,
);
+ const stretchLine = lines.find((line) =>
+ line.trim().startsWith('font-stretch'),
+ );
+ const stretch = stretchLine ? getValue(stretchLine) : null;
const subset =
preliminarySubset ?? '[' + src?.match(/\.([0-9]+)\.woff/)![1] + ']';
@@ -41,7 +45,7 @@ const parseFontFace = (block: string) => {
if (!unicodeRange) throw Error('no unicodeRange');
if (!src) throw Error('no src');
- return {fontFamily, src, unicodeRange, weight, style, subset};
+ return {fontFamily, src, unicodeRange, weight, style, stretch, subset};
};
export type FontInfo = {
@@ -52,6 +56,71 @@ export type FontInfo = {
unicodeRanges: Record<string, string>;
fonts: Record<string, Record<string, Record<string, string>>>;
subsets: string[];
+ variable?: {
+ axes: Record<string, {min: number; max: number}>;
+ fontFaces: {
+ style: string;
+ weight: string;
+ stretch: string | null;
+ subset: string;
+ unicodeRange: string;
+ src: string;
+ }[];
+ url: string;
+ };
+};
+
+export const extractVariableInfoFromCss = ({
+ axes,
+ contents,
+ url,
+}: {
+ axes: {tag: string; start: number; end: number}[];
+ contents: string;
+ url: string;
+}): NonNullable<FontInfo['variable']> => {
+ let remainingContents = contents;
+ const fontFaces: NonNullable<FontInfo['variable']>['fontFaces'] = [];
+
+ while (
+ remainingContents.match(/^\/\*(.*)/) ||
+ remainingContents.match(/^\@font-face/)
+ ) {
+ const endIndex = remainingContents.indexOf('}');
+ const extractedContents = remainingContents.substring(
+ 0,
+ endIndex === -1 ? Infinity : endIndex + 2,
+ );
+ remainingContents = remainingContents.substring(endIndex + 2).trim();
+ const {subset, unicodeRange, style, src, stretch, weight} =
+ parseFontFace(extractedContents);
+ fontFaces.push({
+ style,
+ weight,
+ stretch,
+ subset,
+ unicodeRange,
+ src,
+ });
+
+ if (endIndex === -1) {
+ break;
+ }
+ }
+
+ return {
+ axes: Object.fromEntries(
+ axes.map((axis) => [
+ axis.tag,
+ {
+ min: axis.start,
+ max: axis.end,
+ },
+ ]),
+ ),
+ fontFaces,
+ url,
+ };
};
export const extractInfoFromCss = ({
diff --git a/packages/google-fonts/scripts/generate-index.ts b/packages/google-fonts/scripts/generate-index.ts
index 476b8036c0..937827a0ce 100644
--- a/packages/google-fonts/scripts/generate-index.ts
+++ b/packages/google-fonts/scripts/generate-index.ts
@@ -26,6 +26,18 @@ export type FontInfo = {
unicodeRanges: Record<string, string>;
fonts: Record<string, Record<string, Record<string, string>>>;
subsets: string[];
+ variable?: {
+ axes: Record<string, {min: number; max: number}>;
+ fontFaces: {
+ style: string;
+ weight: string;
+ stretch: string | null;
+ subset: string;
+ unicodeRange: string;
+ src: string;
+ }[];
+ url: string;
+ };
}
export type GoogleFont = {
@@ -47,6 +59,18 @@ export type GoogleFont = {
unicodeRanges: FontInfo['unicodeRanges'];
waitUntilDone: () => Promise<undefined>;
};
+ loadVariableFont?: (
+ style: string,
+ options: {
+ subsets: string[];
+ document?: Document;
+ ignoreTooManyRequestsWarning?: boolean;
+ }
+ ) => {
+ fontFamily: FontInfo['fontFamily'];
+ axes: Record<string, {min: number; max: number}>;
+ waitUntilDone: () => Promise<undefined>;
+ };
};
`;
diff --git a/packages/google-fonts/scripts/generate.ts b/packages/google-fonts/scripts/generate.ts
index 69018740a1..05243d786b 100644
--- a/packages/google-fonts/scripts/generate.ts
+++ b/packages/google-fonts/scripts/generate.ts
@@ -1,10 +1,15 @@
import fs, {mkdirSync} from 'node:fs';
import path from 'path';
import limit from 'p-limit';
-import {FontInfo, extractInfoFromCss} from './extract-info-from-css';
+import {
+ FontInfo,
+ extractInfoFromCss,
+ extractVariableInfoFromCss,
+} from './extract-info-from-css';
import {Font, googleFonts} from './google-fonts';
import {
getCssLink,
+ getVariableCssLink,
quote,
removeWhitespace,
replaceDigitsWithWords,
@@ -63,8 +68,24 @@ const generate = async (font: Font) => {
version: font.version,
subsets: font.subsets,
});
+ const variableUrl = getVariableCssLink(font);
+ if (variableUrl && font.axes) {
+ const variableResponse = await fetch(variableUrl, {
+ headers: {
+ 'User-Agent':
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
+ },
+ });
+ info.variable = extractVariableInfoFromCss({
+ axes: font.axes,
+ contents: await variableResponse.text(),
+ url: variableUrl,
+ });
+ }
- let output = `import { loadFonts } from "./base";
+ let output = `import { loadFonts${
+ info.variable ? ', loadVariableFonts' : ''
+ } } from "./base";
export const getInfo = () => (${JSON.stringify(info, null, 3)})
@@ -94,6 +115,32 @@ export const loadFont = <T extends keyof Variants>(
};
`;
+ if (info.variable) {
+ const styles = [
+ ...new Set(info.variable.fontFaces.map((fontFace) => fontFace.style)),
+ ];
+ output += `type VariableVariants = {\n`;
+ for (const style of styles) {
+ output += ` ${quote(style)}: {\n`;
+ output += ` subsets: ${font.subsets.map(quote).join(' | ')},\n`;
+ output += ` },\n`;
+ }
+
+ output += `};
+
+export const loadVariableFont = <T extends keyof VariableVariants>(
+ style: T,
+ options: {
+ subsets: VariableVariants[T]['subsets'][];
+ document?: Document;
+ ignoreTooManyRequestsWarning?: boolean;
+ }
+) => {
+ return loadVariableFonts(getInfo(), style, options);
+};
+
+`;
+ }
mkdirSync(OUTDIR, {recursive: true});
// Save
@@ -118,9 +165,16 @@ if (!fs.existsSync(CSS_CACHE_DIR)) {
let incompatibleFonts: string[] = [];
const promises: Promise<unknown>[] = [];
+const requestedFamily = process.argv[2] ?? null;
+const fontsToGenerate = requestedFamily
+ ? googleFonts.filter((font) => font.family === requestedFamily)
+ : googleFonts;
+if (fontsToGenerate.length === 0) {
+ throw new Error(`No Google Font named "${requestedFamily}" found`);
+}
// Batch convert
-for (const font of googleFonts) {
+for (const font of fontsToGenerate) {
promises.push(
p(() => {
return generate(font);
@@ -130,9 +184,15 @@ for (const font of googleFonts) {
await Promise.all(promises);
-await Bun.write(
- __dirname + '/incompatible-fonts.ts',
- `export const incompatibleFonts = ${JSON.stringify(incompatibleFonts, null, 2)};`,
-);
+if (!requestedFamily) {
+ await Bun.write(
+ __dirname + '/incompatible-fonts.ts',
+ `export const incompatibleFonts = ${JSON.stringify(
+ incompatibleFonts,
+ null,
+ 2,
+ )};`,
+ );
+}
console.log('- Generated fonts in ' + (Date.now() - date) + 'ms');
diff --git a/packages/google-fonts/scripts/google-fonts.ts b/packages/google-fonts/scripts/google-fonts.ts
index 6d7a3142c9..05fa7dcab2 100644
--- a/packages/google-fonts/scripts/google-fonts.ts
+++ b/packages/google-fonts/scripts/google-fonts.ts
@@ -7,6 +7,8 @@ export type Font = {
version: string;
lastModified: string;
category: string;
+ axes?: {tag: string; start: number; end: number}[];
+ colorCapabilities?: unknown;
files?: unknown;
kind?: unknown;
menu?: unknown;
@@ -24830,6 +24832,10 @@ export const googleFonts: Font[] = [
],
version: 'v42',
lastModified: '2025-09-11',
+ axes: [
+ {tag: 'wdth', start: 62.5, end: 100},
+ {tag: 'wght', start: 100, end: 900},
+ ],
files: {
'100':
'https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9At9Y41P6zHtY.woff2',
diff --git a/packages/google-fonts/scripts/update-font-db.ts b/packages/google-fonts/scripts/update-font-db.ts
index d50790049e..16bf2104c0 100644
--- a/packages/google-fonts/scripts/update-font-db.ts
+++ b/packages/google-fonts/scripts/update-font-db.ts
@@ -2,11 +2,35 @@
import {$} from 'bun';
-const response = await fetch(
- `https://content-webfonts.googleapis.com/v1/webfonts?capability=WOFF2&key=${process.env.GOOGLE_FONTS_API_KEY}`,
-);
+const [staticResponse, variableResponse] = await Promise.all([
+ fetch(
+ `https://content-webfonts.googleapis.com/v1/webfonts?capability=WOFF2&key=${process.env.GOOGLE_FONTS_API_KEY}`,
+ ),
+ fetch(
+ `https://content-webfonts.googleapis.com/v1/webfonts?capability=VF&capability=WOFF2&key=${process.env.GOOGLE_FONTS_API_KEY}`,
+ ),
+]);
-const json = await response.json();
+const staticJson = await staticResponse.json();
+const variableJson = await variableResponse.json();
+const variableFonts = new Map<
+ string,
+ {
+ family: string;
+ axes?: {tag: string; start: number; end: number}[];
+ }
+>(
+ variableJson.items.map(
+ (font: {
+ family: string;
+ axes?: {tag: string; start: number; end: number}[];
+ }) => [font.family, font] as const,
+ ),
+);
+const items = staticJson.items.map((font: {family: string}) => {
+ const axes = variableFonts.get(font.family)?.axes;
+ return axes ? {...font, axes} : font;
+});
const contents = `
// Auto-generated by scripts/update-font-db.ts
@@ -18,12 +42,14 @@ export type Font = {
version: string;
lastModified: string;
category: string;
+ axes?: {tag: string; start: number; end: number}[];
+ colorCapabilities?: unknown;
files?: unknown;
kind?: unknown;
menu?: unknown;
};
-export const googleFonts: Font[] = ${JSON.stringify(json.items, null, 2)};
+export const googleFonts: Font[] = ${JSON.stringify(items, null, 2)};
`.trimStart();
await Bun.write(__dirname + '/google-fonts.ts', contents);
diff --git a/packages/google-fonts/scripts/utils.ts b/packages/google-fonts/scripts/utils.ts
index 8090180cc3..379c962040 100644
--- a/packages/google-fonts/scripts/utils.ts
+++ b/packages/google-fonts/scripts/utils.ts
@@ -41,3 +41,39 @@ export const getCssLink = (font: Font) => {
return url;
};
+
+export const getVariableCssLink = (font: Font) => {
+ if (!font.axes || font.axes.length === 0) {
+ return null;
+ }
+
+ const hasItalic = font.variants.includes('italic');
+ const hasNormal = font.variants.some(
+ (variant) => !variant.endsWith('italic'),
+ );
+ const axes = font.axes
+ .filter((axis) => axis.tag !== 'ital')
+ .map((axis) => ({
+ tag: axis.tag,
+ value:
+ axis.start === axis.end
+ ? String(axis.start)
+ : `${axis.start}..${axis.end}`,
+ }));
+ if (hasItalic) {
+ axes.push({tag: 'ital', value: ''});
+ }
+
+ axes.sort((a, b) => a.tag.localeCompare(b.tag, 'en-US'));
+ const styles = hasItalic ? (hasNormal ? [0, 1] : [1]) : [null];
+ const tuples = styles.map((italic) =>
+ axes
+ .map((axis) => (axis.tag === 'ital' ? String(italic) : axis.value))
+ .join(','),
+ );
+
+ return `https://fonts.googleapis.com/css2?family=${font.family.replace(
+ / /g,
+ '+',
+ )}:${axes.map((axis) => axis.tag).join(',')}@${tuples.join(';')}`;
+};
diff --git a/packages/google-fonts/src/NotoSans.ts b/packages/google-fonts/src/NotoSans.ts
index 8e4150ff12..5aa1db1c1e 100644
--- a/packages/google-fonts/src/NotoSans.ts
+++ b/packages/google-fonts/src/NotoSans.ts
@@ -1,4 +1,4 @@
-import {loadFonts} from './base';
+import {loadFonts, loadVariableFonts} from './base';
export const getInfo = () => ({
fontFamily: 'Noto Sans',
@@ -361,6 +361,161 @@ export const getInfo = () => ({
'latin-ext',
'vietnamese',
],
+ variable: {
+ axes: {
+ wdth: {
+ min: 62.5,
+ max: 100,
+ },
+ wght: {
+ min: 100,
+ max: 900,
+ },
+ },
+ fontFaces: [
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'cyrillic-ext',
+ unicodeRange:
+ 'U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARPQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'cyrillic',
+ unicodeRange: 'U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARGQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'devanagari',
+ unicodeRange:
+ 'U+0900-097F, U+1CD0-1CF9, U+200C-200D, U+20A8, U+20B9, U+20F0, U+25CC, U+A830-A839, U+A8E0-A8FF, U+11B00-11B09',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARDQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'greek-ext',
+ unicodeRange: 'U+1F00-1FFF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4AROQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'greek',
+ unicodeRange:
+ 'U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARBQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'vietnamese',
+ unicodeRange:
+ 'U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARNQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'latin-ext',
+ unicodeRange:
+ 'U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARMQ_m87A.woff2',
+ },
+ {
+ style: 'italic',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'latin',
+ unicodeRange:
+ 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0OIpQlx3QUlC5A4PNr4ARCQ_k.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'cyrillic-ext',
+ unicodeRange:
+ 'U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr6DRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'cyrillic',
+ unicodeRange: 'U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr4TRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'devanagari',
+ unicodeRange:
+ 'U+0900-097F, U+1CD0-1CF9, U+200C-200D, U+20A8, U+20B9, U+20F0, U+25CC, U+A830-A839, U+A8E0-A8FF, U+11B00-11B09',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr5DRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'greek-ext',
+ unicodeRange: 'U+1F00-1FFF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr6TRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'greek',
+ unicodeRange:
+ 'U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr5jRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'vietnamese',
+ unicodeRange:
+ 'U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr6jRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'latin-ext',
+ unicodeRange:
+ 'U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr6zRAW_0.woff2',
+ },
+ {
+ style: 'normal',
+ weight: '100 900',
+ stretch: '62.5% 100%',
+ subset: 'latin',
+ unicodeRange:
+ 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD',
+ src: 'https://fonts.gstatic.com/s/notosans/v42/o-0IIpQlx3QUlC5A4PNr5TRA.woff2',
+ },
+ ],
+ url: 'https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wdth,wght@0,62.5..100,100..900;1,62.5..100,100..900',
+ },
});
export const fontFamily = 'Noto Sans' as const;
@@ -421,3 +576,39 @@ export const loadFont = <T extends keyof Variants>(
) => {
return loadFonts(getInfo(), style, options);
};
+
+type VariableVariants = {
+ italic: {
+ subsets:
+ | 'cyrillic'
+ | 'cyrillic-ext'
+ | 'devanagari'
+ | 'greek'
+ | 'greek-ext'
+ | 'latin'
+ | 'latin-ext'
+ | 'vietnamese';
+ };
+ normal: {
+ subsets:
+ | 'cyrillic'
+ | 'cyrillic-ext'
+ | 'devanagari'
+ | 'greek'
+ | 'greek-ext'
+ | 'latin'
+ | 'latin-ext'
+ | 'vietnamese';
+ };
+};
+
+export const loadVariableFont = <T extends keyof VariableVariants>(
+ style: T,
+ options: {
+ subsets: VariableVariants[T]['subsets'][];
+ document?: Document;
+ ignoreTooManyRequestsWarning?: boolean;
+ },
+) => {
+ return loadVariableFonts(getInfo(), style, options);
+};
diff --git a/packages/google-fonts/src/base.ts b/packages/google-fonts/src/base.ts
index 4edc6963fe..8d86edbfb0 100644
--- a/packages/google-fonts/src/base.ts
+++ b/packages/google-fonts/src/base.ts
@@ -12,6 +12,18 @@ export type FontInfo = {
unicodeRanges: Record<string, string>;
fonts: Record<string, Record<string, Record<string, string>>>;
subsets: string[];
+ variable?: {
+ axes: Record<string, {min: number; max: number}>;
+ fontFaces: {
+ style: string;
+ weight: string;
+ stretch: string | null;
+ subset: string;
+ unicodeRange: string;
+ src: string;
+ }[];
+ url: string;
+ };
};
interface WithResolvers<T> {
@@ -226,3 +238,138 @@ export const loadFonts = (
waitUntilDone: () => Promise.all<void>(promises).then(() => undefined),
};
};
+
+export const loadVariableFonts = (
+ meta: FontInfo,
+ style: string,
+ options: FontLoadOptions & {subsets: string[]},
+): {
+ fontFamily: FontInfo['fontFamily'];
+ axes: Record<string, {min: number; max: number}>;
+ waitUntilDone: () => Promise<undefined>;
+} => {
+ if (!meta.variable) {
+ throw new Error(`${meta.fontFamily} is not available as a variable font`);
+ }
+
+ if (options.subsets.length === 0) {
+ throw new Error('Pass at least one subset to loadVariableFont()');
+ }
+
+ const fontFacesForStyle = meta.variable.fontFaces.filter(
+ (fontFace) => fontFace.style === style,
+ );
+ if (fontFacesForStyle.length === 0) {
+ throw new Error(
+ `The variable font ${meta.fontFamily} does not have a style ${style}`,
+ );
+ }
+
+ const availableSubsetKeys = fontFacesForStyle.map(
+ (fontFace) => fontFace.subset,
+ );
+ const subsets = [
+ ...new Set(
+ options.subsets.flatMap((requestedSubset) =>
+ resolveFontSubsetKeys({
+ availableSubsetKeys,
+ metaSubsets: meta.subsets,
+ requestedSubset,
+ }),
+ ),
+ ),
+ ];
+ const promises: Promise<void>[] = [];
+
+ for (const subset of subsets) {
+ if (typeof FontFace === 'undefined') {
+ continue;
+ }
+
+ const font = fontFacesForStyle.find(
+ (fontFace) => fontFace.subset === subset,
+ );
+ if (!font) {
+ throw new Error(
+ `subset: ${subset} is not available for the variable font '${meta.fontFamily}'`,
+ );
+ }
+
+ const fontKey = [
+ meta.fontFamily,
+ 'variable',
+ font.style,
+ font.weight,
+ font.stretch,
+ font.subset,
+ font.src,
+ ].join('-');
+ const previousPromise = loadedFonts[fontKey];
+ if (previousPromise) {
+ promises.push(previousPromise);
+ continue;
+ }
+
+ const handle = delayRender(
+ `Fetching variable ${meta.fontFamily} font ${JSON.stringify({
+ style,
+ subset,
+ })}`,
+ {timeoutInMilliseconds: 60000},
+ );
+ const descriptors: FontFaceDescriptors = {
+ style: font.style,
+ weight: font.weight,
+ unicodeRange: font.unicodeRange,
+ };
+ if (font.stretch) {
+ descriptors.stretch = font.stretch;
+ }
+
+ const fontFace = new FontFace(
+ meta.fontFamily,
+ `url(${font.src}) format('woff2')`,
+ descriptors,
+ );
+ let attempts = 2;
+
+ const tryToLoad = () => {
+ if (fontFace.status === 'loaded') {
+ continueRender(handle);
+ return;
+ }
+
+ const promise = loadFontFaceOrTimeoutAfter20Seconds(fontFace)
+ .then(() => {
+ (options.document ?? document).fonts.add(fontFace);
+ continueRender(handle);
+ })
+ .catch((err) => {
+ loadedFonts[fontKey] = undefined;
+ if (attempts === 0) {
+ throw err;
+ }
+
+ attempts--;
+ tryToLoad();
+ });
+
+ loadedFonts[fontKey] = promise;
+ promises.push(promise);
+ };
+
+ tryToLoad();
+ }
+
+ if (subsets.length > 20 && !options.ignoreTooManyRequestsWarning) {
+ console.warn(
+ `Made ${subsets.length} network requests to load the variable font ${meta.fontFamily}. Consider loading fewer subsets. Disable this warning by passing "ignoreTooManyRequestsWarning: true" to "options".`,
+ );
+ }
+
+ return {
+ fontFamily: meta.fontFamily,
+ axes: meta.variable.axes,
+ waitUntilDone: () => Promise.all<void>(promises).then(() => undefined),
+ };
+};
diff --git a/packages/google-fonts/src/index.ts b/packages/google-fonts/src/index.ts
index 4f227ea2e5..f6dbb6ffcc 100644
--- a/packages/google-fonts/src/index.ts
+++ b/packages/google-fonts/src/index.ts
@@ -17,6 +17,18 @@ export type FontInfo = {
unicodeRanges: Record<string, string>;
fonts: Record<string, Record<string, Record<string, string>>>;
subsets: string[];
+ variable?: {
+ axes: Record<string, {min: number; max: number}>;
+ fontFaces: {
+ style: string;
+ weight: string;
+ stretch: string | null;
+ subset: string;
+ unicodeRange: string;
+ src: string;
+ }[];
+ url: string;
+ };
};
export type GoogleFont = {
@@ -38,6 +50,18 @@ export type GoogleFont = {
unicodeRanges: FontInfo['unicodeRanges'];
waitUntilDone: () => Promise<undefined>;
};
+ loadVariableFont?: (
+ style: string,
+ options: {
+ subsets: string[];
+ document?: Document;
+ ignoreTooManyRequestsWarning?: boolean;
+ },
+ ) => {
+ fontFamily: FontInfo['fontFamily'];
+ axes: Record<string, {min: number; max: number}>;
+ waitUntilDone: () => Promise<undefined>;
+ };
};
export const getAvailableFonts = () => [
diff --git a/packages/google-fonts/test/generate-info.test.ts b/packages/google-fonts/test/generate-info.test.ts
index 85420c6f32..bf859ab37d 100644
--- a/packages/google-fonts/test/generate-info.test.ts
+++ b/packages/google-fonts/test/generate-info.test.ts
@@ -1,5 +1,9 @@
import {test, expect} from 'bun:test';
-import {extractInfoFromCss} from '../scripts/extract-info-from-css';
+import {
+ extractInfoFromCss,
+ extractVariableInfoFromCss,
+} from '../scripts/extract-info-from-css';
+import {getVariableCssLink} from '../scripts/utils';
const testFile = `
/* latin-ext */
@@ -77,3 +81,66 @@ test('Should extract correctly', () => {
subsets: ['latin', 'latin-ext'],
});
});
+
+test('Should generate and extract variable font information', () => {
+ const font = {
+ family: 'Roboto Flex',
+ variants: ['regular'],
+ subsets: ['latin'],
+ version: 'v30',
+ lastModified: '2025-09-08',
+ category: 'sans-serif',
+ axes: [
+ {tag: 'opsz', start: 8, end: 144},
+ {tag: 'wdth', start: 25, end: 151},
+ {tag: 'wght', start: 100, end: 1000},
+ ],
+ };
+ const url = getVariableCssLink(font);
+ expect(url).toBe(
+ 'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wdth,[email protected],25..151,100..1000',
+ );
+ expect(
+ getVariableCssLink({
+ ...font,
+ family: 'Noto Sans',
+ variants: ['regular', 'italic'],
+ axes: [{tag: 'wght', start: 100, end: 900}],
+ }),
+ ).toBe(
+ 'https://fonts.googleapis.com/css2?family=Noto+Sans:ital,wght@0,100..900;1,100..900',
+ );
+
+ expect(
+ extractVariableInfoFromCss({
+ axes: font.axes,
+ contents: `/* latin */
+@font-face {
+ font-family: 'Roboto Flex';
+ font-style: normal;
+ font-weight: 100 1000;
+ font-stretch: 25% 151%;
+ src: url(https://fonts.gstatic.com/roboto-flex.woff2) format('woff2');
+ unicode-range: U+0000-00FF;
+}`,
+ url: url as string,
+ }),
+ ).toEqual({
+ axes: {
+ opsz: {min: 8, max: 144},
+ wdth: {min: 25, max: 151},
+ wght: {min: 100, max: 1000},
+ },
+ fontFaces: [
+ {
+ style: 'normal',
+ weight: '100 1000',
+ stretch: '25% 151%',
+ subset: 'latin',
+ unicodeRange: 'U+0000-00FF',
+ src: 'https://fonts.gstatic.com/roboto-flex.woff2',
+ },
+ ],
+ url,
+ });
+});
diff --git a/packages/google-fonts/test/variable-font.test.ts b/packages/google-fonts/test/variable-font.test.ts
new file mode 100644
index 0000000000..2cde91ec62
--- /dev/null
+++ b/packages/google-fonts/test/variable-font.test.ts
@@ -0,0 +1,66 @@
+import {expect, mock, test} from 'bun:test';
+
+mock.module('remotion', () => ({
+ continueRender: () => undefined,
+ delayRender: () => 0,
+}));
+mock.module('remotion/no-react', () => ({
+ NoReactInternals: {
+ ENABLE_V5_BREAKING_CHANGES: false,
+ },
+}));
+
+test('loads a variable font face with its weight range', async () => {
+ const {loadVariableFont} = await import('../src/NotoSans');
+ const originalFontFace = globalThis.FontFace;
+ let descriptors: FontFaceDescriptors | null = null;
+ let addedFontFace: FontFace | null = null;
+
+ class MockFontFace {
+ status: FontFaceLoadStatus = 'unloaded';
+
+ constructor(
+ _fontFamily: string,
+ _source: string,
+ fontDescriptors?: FontFaceDescriptors,
+ ) {
+ descriptors = fontDescriptors ?? null;
+ }
+
+ load() {
+ this.status = 'loaded';
+ return Promise.resolve(this);
+ }
+ }
+
+ globalThis.FontFace = MockFontFace as unknown as typeof FontFace;
+
+ try {
+ const document = {
+ fonts: {
+ add: (fontFace: FontFace) => {
+ addedFontFace = fontFace;
+ },
+ },
+ } as unknown as Document;
+ const loaded = loadVariableFont('normal', {
+ document,
+ subsets: ['latin'],
+ });
+
+ expect(loaded.fontFamily).toBe('Noto Sans');
+ expect(loaded.axes.wdth).toEqual({min: 62.5, max: 100});
+ expect(loaded.axes.wght).toEqual({min: 100, max: 900});
+ await loaded.waitUntilDone();
+ expect(descriptors).toEqual({
+ stretch: '62.5% 100%',
+ style: 'normal',
+ unicodeRange:
+ 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD',
+ weight: '100 900',
+ });
+ expect(addedFontFace).toBeInstanceOf(MockFontFace);
+ } finally {
+ globalThis.FontFace = originalFontFace;
+ }
+});