Jayed Rashid

Welcome aboard..

Let's Connect

New Next JS Metadata

Next JS changed their metadata as well as head tag

Getting Started

Next JS Metadata

Next Js has a Metadata API that can be used to define your application metadata for improved SEO and web shareability.

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 { Metadata } from 'next';
 
export const metadata: Metadata = {
  title: 'Title',
  description: 'Description',
}
 
export default function Page() {}

Dynamic Metadata

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

import { 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) {}

Note: Both static and dynamic metadata through generateMetadata are only supported in Server Components.

Learn More

You can learn more from New Next Metadata.

Connect with me ^_^

If you like this article, kindly follow my github account for more and be sure to ⭐ it.

Jayed Rashid

© JayedRashid 2023. All rights reserved