All you need to know about metadata in next.js 13 by Anik Routh

Anik RouthAnik Routh
3 min read

Introduction:

Next.js 13 introduces a powerful Metadata API that enhances your application's SEO and web shareability by allowing you to define metadata such as meta and link tags within your HTML head element.

Changes Made:

  • Replaced "has" with "introduces a powerful" to emphasize the significance of the Metadata API.

  • Added "enhances your application's" to specify the benefits of using the Metadata API.

  • Changed "can be used to define" to "by allowing you to define" for a more active voice..

There are two ways you can add metadata to your application:

Static metadata:

To define static metadata, export a Metadata object from a layout.js or static page.js file.

import type { Metadata } from 'next' 

export const metadata: Metadata = { 
  title: '...', 
  description: '...', 
} 

export default function Page() {
  .....
}

Next.js will automatically generate the relevant <head> elements for your pages. You can also create dynamic OG images using the ImageResponse constructor.

For all the available options, see the API Reference.

Dynamic metadata:

You can use generateMetadata function to fetch metadata that requires dynamic values.

import type { Metadata, ResolvingMetadata } from 'next'

type Props = {
  params: { id: string }
  searchParams: { [key: string]: string | string[] | undefined }
}

export async function generateMetadata(
  { params, searchParams }: Props,
  parent?: ResolvingMetadata
): Promise<Metadata> {
  // read route params
  const id = params.id

  // fetch data
  const product = await fetch(`https://.../${id}`).then((res) => res.json())

  // optionally access and extend (rather than replace) parent metadata
  const previousImages = (await parent).openGraph?.images || []

  return {
    title: product.title,
    openGraph: {
      images: ['/some-specific-page-image.jpg', ...previousImages],
    },
  }
}

export default function Page({ params, searchParams }: Props) {}

Good to know:

  • Both static and dynamic metadata generateMetadata are only supported in Server Components.

  • fetch requests are automatically memoized for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable.

  • Next.js will wait for data fetching inside generateMetadata to complete before streaming UI to the client. This guarantees the first part of a streamed response includes <head> tags.

Dynamic Image Generation:

The ImageResponse constructor allows you to generate dynamic images using JSX and CSS. This is useful for creating social media images such as Open Graph images, Twitter cards, and more.

ImageResponse uses the Edge Runtime, and Next.js automatically adds the correct headers to cached images at the edge, helping improve performance and reducing recomputation.

To use it, you can import ImageResponse from next/server:

import { ImageResponse } from 'next/server'

export const runtime = 'edge'

export async function GET() {
  return new ImageResponse(
    (
      <div
        style={{
          fontSize: 128,
          background: 'white',
          width: '100%',
          height: '100%',
          display: 'flex',
          textAlign: 'center',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        Hello world!
      </div>
    ),
    {
      width: 1200,
      height: 600,
    }
  )
}

ImageResponse integrates well with other Next.js APIs, including Route Handlers and file-based Metadata. For example, you can use ImageResponse it in a opengraph-image.tsx file to generate Open Graph images at build time or dynamically at request time.

ImageResponse supports common CSS properties including flexbox and absolute positioning, custom fonts, text wrapping, centering, and nested images. See the full list of supported CSS properties.

Examples are available in the Vercel OG Playground.

Follow me on Medium for more.

Thank you for reading my post! Here is my website check it out.

Thank you for reading my post! Here is my website check it out.

0
Subscribe to my newsletter

Read articles from Anik Routh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anik Routh
Anik Routh