tl;dr
Next.js 13's /app
router's layout
and page
routing changes how we add content to the <head>
. How can I add a schema script to each page? Next.js will automatically compile <head>
tags placed in any layout
or page
into a single <head>
.
The goal
Just like in any website with great SEO, I want to include a schema script in the head of each page.
The history
Normally, this would be as easy as writing it in the <head>
like so:
<!-- index.html -->
<head>
<script type="application/ld+json">
{
"@context": "https://schema.org",
// ... the rest
}
</script>
</head>
Then, with the Next.js /pages
directory it was a little different. It always felt weird to me to have to use the dangerouslySetInnerHTML
attribute, but at least it worked.
// index.tsx
import Head from 'next/head'
export default function Page() {
return (
<Head>
<script id="schema" type="application/ld+json" dangerouslySetInnerHTML={{__html: `
{
"@context": "https://schema.org",
// ... the rest
}
`}} />
</Head>
)
}
The issue
Now with the introduction of the /app
router, we've got great, new, simplified ways to set metadata, without having to directly import the <head>
through next/head
. In fact, the next/head
component shouldn't be used in the /app
router.
So the question becomes...
How do we access the <head>
on a page-per-page basis?
I was hoping the Next.js team would have already thought about this, and added schema to the new metadata
variable, or even it's own variable, but they don't seem to have plans to do this as far as I can tell.
I tried adding a <head>
to the page
and unfortunately, it doesn't properly merge into the <head>
. So far the only thing I can thing to do would be to add the schema to each layout
, but what a hassle that would be to have an individual layout for each page.
Any ideas are welcome.
<head>
. That's super helpful.