空雲 Blog

Eye catch
Cloudflare Fonts を Reactから使用する

publication: 2025/02/20
update:2025/02/20

コード置き場🔗


https://github.com/ReactLibraries/cloudflare-fonts


Cloudflare Fonts とは🔗


Cloudflare Fonts は、Google Fonts を使用する場合に、HTML 上の link タグを読み取り、style タグに変換して対象のフォントイメージのアドレスをインライン展開します。またイメージのリンク先は Cloudflare の高速な CDN(Content Delivery Network)を使用しているため、ページロードが高速になります。


ただしこの機能は React の SSR と相性が悪く、出力した HTML 上のタグが書き換えられてしまうため、クライアント側でハイドレーションするときに不整合を起こして、全体が再レンダリングの対象となってしまい、チラツキやパフォーマンスの低下を起こします。


不整合を抑える方法🔗


Cloudflare Fonts が行うのは head タグの中にある、GoogleFont 呼び出しの link タグの削除と style タグの挿入です。そしてハイドレーションエラーになる原因は、link タグが消えてその部分をマウントできないために起こります。追加された style に関しては、仮想 DOM 側に割り当てるものがなくとも華麗にスルーされ、特にエラーにはなりません。つまり link タグだけクライアント側の仮想 DOM から削除すれば問題解決です。


対応コードを作る🔗


フォントの読み込みを制御するための React コンポーネントを作ります。このコンポーネントは、サーバ側では通常通り link タグを生成し、クライアント側では link タグを削除します。ただしローカル環境や Cloudflare Font が有効になっていない場合などに問題が起こらないように、style タグの中を確認して、変換が行われているかどうかを確認しています。


1import React from "react";
2import { useRef, type FC } from "react";
3
4type FontProperty = {
5 isLoaded?: boolean;
6 isData?: boolean;
7};
8
9const isServer = typeof window === "undefined";
10
11export const CloudflareFonts: FC<{ href: string | string[] }> = ({ href }) => {
12 const property = useRef<FontProperty>({}).current;
13 if (!property.isLoaded && !isServer) {
14 property.isLoaded = true;
15 const nodes = document.querySelectorAll("head style[type='text/css']");
16 property.isData = Array.from(nodes).some((v) =>
17 v.textContent?.includes("url(/cf-fonts/")
18 );
19 }
20 if (!property.isData) {
21 const urls = Array.isArray(href) ? href : [href];
22 return (
23 <>
24 <link rel="preconnect" href="https://fonts.googleapis.com" />
25 <link
26 rel="preconnect"
27 href="https://fonts.gstatic.com"
28 crossOrigin="anonymous"
29 />
30 {urls.map((href) => (
31 <link key={href} rel="stylesheet" href={href} />
32 ))}
33 </>
34 );
35 }
36 return null;
37};


使い方🔗


react router で使う場合の抜粋です。Cloudflare Fonts コンポーネントにフォントのアドレスを指定するだけです。
注意点として、これを有効にするためには、Cloudflare 側のカスタムドメインの設定で Cloudflare Fonts を有効にする必要があります。


1import { CloudflareFonts } from "cloudflare-fonts";
2
3export function Layout({ children }: { children: React.ReactNode }) {
4 return (
5 <html lang="en">
6 <head>
7 <meta charSet="utf-8" />
8 <meta name="viewport" content="width=device-width, initial-scale=1" />
9 <Meta />
10 <Links />
11 <CloudflareFonts
12 href={[
13 "https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&display=swap",
14 "https://fonts.googleapis.com/css2?family=Kaisei+Decol&display=swap",
15 "https://fonts.googleapis.com/css2?family=Dela+Gothic+One&display=swap",
16 ]}
17 />
18 </head>
19 <body>
20 {children}
21 <ScrollRestoration />
22 <Scripts />
23 </body>
24 </html>
25 );
26}


実行結果🔗


ブラウザ上で要素を確認すると、きちんと変換されたフォントデータが展開されたままになっています。


{"width":"1345px","height":"949px"}


まとめ🔗


Web Font を利用しつつ、サイトの表示を少しでも高速化したいという場合にこの方法が有効です。