Next.js Discord

Discord Forum

Insert JSON+LD Schema in head from page in app router

Answered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
Any way to insert a custom <script> tag from a page ?
What's the correct way to insert JSON+LD schema from a page using app router (Since next/head isn't supported in app router)
Answered by Ray
yes
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>
  )
}
View full answer

8 Replies

@Masai Lion Any way to insert a custom <script> tag from a page ? What's the correct way to insert JSON+LD schema from a page using app router (Since next/head isn't supported in app router)
yes
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>
  )
}
Answer
Masai LionOP
Yes i saw that but this inject the script inside the page. Is it possible to inject it inside <head> tag.
I'm not sure about best practice for json-ld ....
Masai LionOP
Ok, so sound good 🙂
Thanks @Ray !