Custom Fonts with Next 13 and MUI
NextJS 13 launches with an excellent new font loading pattern. This article will explain how to integrate this font loading pattern in your MaterialUI themes. Reading and understanding this official documentation from Next is important as an initial launch point for this article.
1. Adding @next/font
Follow the Next documentation to add the @next/font library via npm or yarn to your project.
2. Diverge from documentation
In the initial example, the Next documentation recommends importing and adding our custom font to the _app.js file like so:
// pages/_app.js
import { Inter } from '@next/font/google'
// If loading a variable font, you don't need to specify the font weight
const inter = Inter({ subsets: ['latin'] })
export default function MyApp({ Component, pageProps }) {
return (
<main className={inter.className}>
<Component {...pageProps} />
</main>
)
}
Let’s replace this code with a simplified example that uses a MaterialUI theme as a wrapper:
//pages/_app.js
import { ThemeProvider } from "@mui/material";
import { lightTheme } from '../themes/light.theme'
export default function App({ Component, pageProps }) {
return (
<ThemeProvider theme={lightTheme}>
<Component {...pageProps} />
</ThemeProvider>
)
}
3. Implement fonts inside theme
// themes/lightTheme
import { createTheme } from "@mui/material";
import { Roboto } from '@next/font/google'
export const roboto = Roboto({
weight: '400',
subsets: ['latin'],
})
export const lightTheme = createTheme({
typography: {
fontFamily:
roboto.style.fontFamily,
body1: {
fontFamily: roboto.style.fontFamily,
},
// etc
}
});
And there you have it! Your custom font has been imported and added to your MaterialUI Theme, available throughout your application.
Top comments (0)