Based on the knowledge sources provided, there isn't a direct method for lazy loading local fonts dynamically based on user settings in Next.js. The next/font module is designed to optimize fonts by preloading them at build time rather than loading them on-demand.
When using next/font/local, fonts are preloaded based on where they're used:
- If used in a unique page, the font is preloaded only on that route
- If used in a layout, it's preloaded on all routes wrapped by that layout
- If used in the root layout, it's preloaded on all routes
There are a few challenges with implementing dynamic font loading based on user settings:
-
The preload option in next/font/local accepts a boolean value, but attempting to use a dynamic expression (like a ternary) can cause errors as noted in a GitHub issue next/font/local dynamic preload.
-
Font declarations are typically made at the component level and are processed at build time, not runtime.
A potential workaround might be to:
- Define all your font options using
next/font/local
- Use CSS variables approach as mentioned in the documentation for using multiple fonts
- Dynamically apply the appropriate font class based on user settings
For example:
import localFont from 'next/font/local'
export const fontA = localFont({
src: './fontA.woff2',
variable: '--font-a',
})
export const fontB = localFont({
src: './fontB.woff2',
variable: '--font-b',
})
import { fontA, fontB } from './fonts'
import { useState, useEffect } from 'react'