Ben Winding
Ben Winding

Reputation: 11807

Next.js 13 - How can I add a custom json script tag to each page

Context

Goal

To add schema.json within a <script> tag on each page:

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Thing",
  ...
}
</script>

Solution Attempts

Any ideas on how to add <script type="application/ld+json"> server-side for each page?

Upvotes: 2

Views: 2247

Answers (3)

Stefan
Stefan

Reputation: 974

This is the official solution:

export default async function Page({ params }) {
  const product = await getProduct(params.id)
 
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.name,
    image: product.image,
    description: product.description,
  }
 
  return (
    <section>
      {/* Add JSON-LD to your page */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      {/* ... */}
    </section>
  )
}

Upvotes: 1

Matheus Kroska
Matheus Kroska

Reputation: 21

I managed to make it work for my use case; it appends to the head and can be used either in layout or pages


export default function RootLayout() {
          return (
            <>
              <head>
                <script
                  id="schema-jsonld"
                  type="application/ld+json"
                  dangerouslySetInnerHTML={{
                    __html: JSON.stringify(structuredData, null, "\t"),
                  }}
                />
              </head>
              <html>...</html>
            </>
          );
        }

Upvotes: 0

Ben Winding
Ben Winding

Reputation: 11807

For Future Readers

Okay, seems it's not supported in the head yet (discussion for feature on Github)

Basically in [email protected] you need to add the Schema.Org json script tag to the page body, not to the head

export default function Page() {
  return (
    <>
      <script
        key="schema-jsonld"
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaJsonObj, null, "\t") }}
      />
     ....

It will still be read by search engines, but hopefully it will be possible to add to the <head> soon 🙏

Upvotes: 0

Related Questions