Hello, I have a CMS system setup where the user can select a predefined set of fonts. On my root layout.tsx I fetch the font name with custom function getFont() which returns a font key for example: "inter", "playfair", etc. Is it possible to somehow dynamically import only the font selected by user and use it in my app without hurting the performance by importing a buch of predefined ones?
#How to dynamically import fonts?
1 messages · Page 1 of 1 (latest)
🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord
🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize
✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)
next/font is certainly out of the question here. i also faced this problem before and i just used the google fonts api (iirc) to get the font css url and then use a <link> in your root layout to use that url
you can use other apis as well, for example fontsource or any method you know of to retrieve the css file url
you can also use cloudflare fonts if you use cloudflare; in that case you may find this snippet helpful
so for example like this:
// lib/fonts.ts
export function getFontUrl(fontName: string): string {
const fontMap: { [key: string]: string } = {
inter: 'Inter:wght@400;700',
playfair: 'Playfair+Display:wght@400;700',
roboto: 'Roboto:wght@400;500',
};
const formattedFont = fontMap[fontName] || fontMap.inter;
return `https://fonts.googleapis.com/css2?family=${formattedFont}&display=swap`;
}
// app/layout.tsx
export default async function RootLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
const fontUrl = getFontUrl("inter")
return (
<html
lang="en"
suppressHydrationWarning
>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
<link href="${fontUrl}" rel="stylesheet" />
`,
}}
/>
</head>
<body>
{children}
</body>
</html>
);
}
if you dont use cloudflare fonts or a proxy that changes the <link> tag without nextjs knowing, you don't need to use the <script> trick, you can just <link href={...} /> directly
but yes basically you get the css url from somewhere and render it