DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on • Edited on

Optimizing Fonts and Images (Next.js)

You can visit my GitHub repo to follow along with me.

Custom fonts can affect performance if the font files need to be fetched and loaded.

Cumulative Layout Shift is a measure of website performance.

The Next.js next/font module automatically optimizes fonts. It downloads font files at build time and hosts them with static assets so there are no additional network requests for fonts.

Adding a primary font

Use /app/ui/fonts.ts to keep the fonts that will be used.

Adding Inter to the <body> element, applies the font throughout. The Tailwind antialiased class smooths out the font.

Adding a secondary font

If you're unsure what weight options to pass to a font, check the TypeScript errors in your code editor.

Visit Google Fonts and search for Lusitana to see what options are available.

See the documentation for adding multiple fonts and the full list of options.

Optimize Images

Next.js can serve static assets, like images, under the top-level /public folder. Files inside /public can be referenced in your application.

With regular HTML, you manually:

  • Ensure your image is responsive on different screen sizes.
  • Specify image sizes for different devices.
  • Prevent layout shift as the images load.
  • Lazy load images that are outside the user's viewport.

The next/image component automatically optimizes your images. The <Image> Component is an extension of the HTML <img> tag, and comes with automatic image optimization, such as:

  • Preventing layout shift automatically when images are loading.
  • Resizing images to avoid shipping large images to devices with a smaller viewport.
  • Lazy loading images by default (images load as they enter the viewport).
  • Serving images in modern formats, like WebP and AVIF, when the browser supports it.

Good practice:

  • Set the width and height of your images to avoid layout shift
  • Aspect ratio identical to the source image.

Dive deeper into fonts and images:

https://nextjs.org/docs/app/building-your-application/optimizing/images

https://nextjs.org/docs/app/building-your-application/optimizing/fonts

https://developer.mozilla.org/en-US/docs/Learn/Performance/Multimedia

https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Web_fonts

Top comments (0)