Optimized image and font loading in Next.js
Loading images and fonts in an optimized way can be tedious, but Next.js makes it very simple by providing the Font
and Image
components.
The Font component
Often, you’ll want to use a specific font for your page to make it unique and stand out. If your font is on Google Fonts, you can have Next.js automatically self-host it for you. No requests will be sent to Google by your browser if you use this feature. Additionally, the fonts will be loaded optimally with zero layout shift.
Let’s find out how Google Fonts can be self-hosted with Next.js:
- We are going to load the
Inter
font by importing it fromnext/font/google
. Editsrc/app/layout.js
and add the following import:import { Inter } from 'next/font/google'
- Now, load the font, as follows:
const inter = Inter({ subsets: ['latin'], display: 'swap', })
Inter
is a variable font, so we don’t need to specify...