Metadata, images & fonts
Add SEO metadata and optimise images and fonts with the built-in components.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
Next.js has built-in tools for page metadata, images and fonts. They improve SEO and sharing previews, and they prevent slow loads and layout shifts with little effort.
Explained simply
When someone shares your page on social media or finds it on Google, they first see its title, description and a preview image. This information is called metadata. Next.js lets you set it for each page with a simple exported object.
Images are often the heaviest part of a page. The Next.js Image component resizes each image for the visitor's screen, converts it to modern formats like WebP or AVIF, and loads images below the fold only when the user scrolls near them.
Fonts can cause text to jump when they finish loading, or to be invisible for a moment. next/font downloads the font files when you build, serves them from your own site, and adjusts the fallback font so the swap barely moves anything.
Together these three tools improve search results and sharing previews, and they help your Core Web Vitals scores, which measure how fast and stable a page feels.
Press Play on a diagram to walk through it one step at a time.
- Metadata
- static metadata export
- generateMetadata for dynamic pages
- Open Graph images
- next/image
- Resizes per device
- Lazy loads by default
- Reserves space to avoid shift
- next/font
- Self-hosts font files
- No layout shift on swap
- No runtime font requests
- One full-size file for every screen
- No reserved space unless you add it
- Font loads from a third-party server
- Text can jump when the font swaps
- Resized per screen, modern formats
- Space reserved from width and height
- Font self-hosted from your domain
- Fallback metrics adjusted to limit shift
In depth
Metadata: static, dynamic and inherited
Export a metadata object from a layout.tsx or page.tsx. Metadata merges down the tree: the root layout can set defaults, and pages override fields. A title template saves repetition: title: { template: "%s | Recipes", default: "Recipes" } in the root layout makes a page titled "Pasta" show as "Pasta | Recipes". Set metadataBase to your site URL once, so relative image URLs in openGraph become absolute, which social networks require.
When metadata depends on data, export async function generateMetadata({ params }) instead. It runs on the server, can fetch the same data as the page (fetch calls are deduplicated, and you can wrap database calls in React's cache), and returns the same shape. Only server components can export metadata.
- Root layout: metadataBase, title template, defaults
- Pages: title, description, openGraph, alternates.canonical
- Dynamic pages: generateMetadata({ params })
- robots: { index: false } for private pages
File-based metadata
Some metadata is easier as files in the app directory. favicon.ico, icon.png and apple-icon.png become the right link tags automatically. opengraph-image.png (or .jpg) in a segment becomes that route's share image. For per-page images, opengraph-image.tsx can generate one with ImageResponse from next/og, drawing the post title on a template at request or build time.
sitemap.ts returns a list of URLs with lastModified dates, and robots.ts returns rules plus the sitemap URL; Next.js serves them at /sitemap.xml and /robots.txt. Generating the sitemap from the same data as your pages means new pages are listed automatically.
- favicon.ico, icon.png
- Browser tab icons
- opengraph-image.tsx
- Generated share image with next/og
- sitemap.ts
- Served at /sitemap.xml
- robots.ts
- Served at /robots.txt
- blog/[slug]/opengraph-image.tsx
- One image per post
How next/image optimizes
The Image component renders an img tag with a srcset: several sizes of the same picture. The browser picks the smallest one that fits the screen, and the Next.js image optimizer (or your host's) creates those sizes on demand and caches them. It serves WebP or AVIF when the browser supports them.
It also prevents layout shift. With width and height, it reserves the right space before the image loads. With fill, the image covers its parent, which must have position relative and a size, and you should pass sizes, such as sizes="(max-width: 768px) 100vw, 50vw", so the browser does not download a full-width image for a half-width slot. Images are lazy loaded by default. Mark the main above-the-fold image with priority so it loads early, which helps Largest Contentful Paint. Remote images need their hosts listed in images.remotePatterns in next.config.
- Step 1Render
img with srcset and reserved space
- Step 2Browser picks
Smallest size for screen and sizes
- Step 3Optimizer
Resizes, converts to WebP or AVIF
- Step 4Cache
Later requests served from cache
How next/font avoids layout shift
Fonts from next/font/google are downloaded at build time and served from your domain, so the browser makes no request to Google and no visitor data goes there. The CSS is generated with font-display: swap by default and a fallback font tuned with size-adjust, so the text takes nearly the same space before and after the real font arrives.
Call the font function once at module level, for example in the root layout, and pass subsets: ["latin"] to keep files small. Variable fonts give every weight in one file. Use the className on an element, or the variable option, such as variable: "--font-sans", to expose a CSS custom property you can use in Tailwind or plain CSS. For your own font files, next/font/local takes a src path.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Add static and dynamic metadata~40m
- 2Optimise images with next/image~40m
- 3Load fonts with next/font~40m
Key points
- Export a metadata object from a layout or page to set title and description.
- Use generateMetadata when metadata depends on route params or fetched data.
- next/image needs width and height, or fill, so it can reserve space.
- Mark the main above-the-fold image as priority to speed up LCP.
Key terms
Tap a card to flip it. 0/5 known
Examples
import Image from 'next/image';
import { Inter } from 'next/font/google';
import type { Metadata } from 'next';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = { title: 'Recipes', description: 'Weeknight recipes' };
export default function Page() {
return (
<main className={inter.className}>
<Image src="/hero.jpg" alt="Pasta on a table" width={1200} height={600} priority />
</main>
);
}Static metadata, an optimised hero image and a self-hosted font.
Metadata for a blog post page
Step 1: in the root layout, set metadataBase and a title template. Step 2: in the post page, generateMetadata awaits params and loads the post; the page can call the same getPost, deduplicated by React's cache. Step 3: return title, description, a canonical URL and Open Graph data. The browser tab shows "How to boil pasta | Recipes", and shares show the post's image.
// app/blog/[slug]/page.tsx
import type { Metadata } from "next";
import { getPost } from "@/lib/posts";
type Props = { params: Promise<{ slug: string }> };
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { slug } = await params;
const post = await getPost(slug);
return {
title: post.title,
description: post.excerpt,
alternates: { canonical: `/blog/${slug}` },
openGraph: { type: "article", images: [post.coverUrl] },
};
}A responsive hero image and a variable font
Step 1: load Inter once in the root layout with a CSS variable. Step 2: the hero uses fill inside a positioned box with a fixed aspect ratio, so no layout shift. Step 3: sizes tells the browser the image is full width on phones and half width on desktops. Step 4: priority loads it early because it is the LCP element.
// app/layout.tsx: const inter = Inter({ subsets: ["latin"], variable: "--font-sans" });
// <html className={inter.variable}> ... then use font-family: var(--font-sans)
import Image from "next/image";
export function Hero() {
return (
<div style={{ position: "relative", aspectRatio: "16 / 9" }}>
<Image src="/hero.jpg" alt="A bowl of fresh pasta" fill priority
sizes="(max-width: 768px) 100vw, 50vw" style={{ objectFit: "cover" }} />
</div>
);
}Quick reference
- export const metadata = { title, description } in a server layout or page
- Root layout: title: { template: "%s | Site", default: "Site" } and metadataBase
- generateMetadata({ params }) for data-driven titles and descriptions
- app/sitemap.ts and app/robots.ts serve /sitemap.xml and /robots.txt
- Image needs width and height, or fill inside a positioned parent plus sizes
- Only the main above-the-fold image gets priority; the rest lazy load
- List remote image hosts in images.remotePatterns in next.config
- next/font self-hosts fonts at build time; use variable: "--font-x" for CSS
Common mistakes
- Using the same title on every page, which hurts search results.
- Leaving off width and height, causing layout shift or build errors.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add metadata to app/about/page.tsx with the title About us and a short description.
- Exercise 2medium
Write app/sitemap.ts that lists the home page and every blog post from getAllPosts(), each with lastModified.
- Exercise 3hard
Create app/blog/[slug]/opengraph-image.tsx that generates a 1200x630 image with the post title on a dark background.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Why is my Next.js image blurry or too large?
- Usually the sizes prop is missing or wrong with fill, so the browser picks the wrong file. Set sizes to match how wide the image really appears at each breakpoint.
- Do I need a favicon in the public folder?
- No. Put favicon.ico or icon.png in the app directory and Next.js adds the right tags for you.
- Does next/font send requests to Google Fonts?
- No. Google fonts are downloaded at build time and served from your own domain.