How to create meta tags dynamically in Next.js?

by aniyah.green , in category: SEO , 3 days ago

How to create meta tags dynamically in Next.js?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by julio , 2 days ago

@aniyah.green 

Creating meta tags dynamically in a Next.js application can be achieved using the next/head module, which allows you to modify the <head> section of your HTML document.


Here's a step-by-step guide on how to accomplish this:

1. Import Head from next/head

You need to import the Head component from the next/head package. This component allows you to add elements like <title>, <meta>, and other tags to the <head> of your page.

1
import Head from 'next/head';


2. Use Head in Your Component

Include the Head component within your page component and dynamically set the meta tags based on the content or state of the page. For instance, you might have a page where the title or meta description depends on props passed to the page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const Page = ({ title, description }) => {
  return (
    <>
      <Head>
        <title>{title}</title>
        <meta name="description" content={description} />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta charSet="UTF-8" />
        {/* Add more meta tags as needed */}
      </Head>
      <div>
        <h1>{title}</h1>
        <p>{description}</p>
      </div>
    </>
  );
};

export default Page;


3. Pass Dynamic Props

Make sure the props passed to the component are dynamic. This could be achieved through a variety of methods, such as fetching data from an API or using Next.js's data fetching methods like getStaticProps or getServerSideProps.

Using getStaticProps

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
export const getStaticProps = async () => {
  // Fetch data from an API or define it here
  const title = "Dynamic Page Title";
  const description = "This is a dynamic description for the page.";

  return {
    props: {
      title,
      description,
    },
  };
};


Using getServerSideProps

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
export const getServerSideProps = async () => {
  // Fetch data from an API or perform some server-side logic
  const title = "Dynamic Page Title from Server Side";
  const description = "Dynamic description retrieved from a server-side function.";

  return {
    props: {
      title,
      description,
    },
  };
};


By following these steps, you can dynamically set the meta tags for each page based on the specific content, improving SEO and providing a more tailored experience for users based on the page they visit. Adjust the attributes and content of the tags according to your specific needs.