Summary:
In Next.js 13, the /app
router's new changes to layout
and page
routing have altered how we add content to the <head>
. The challenge now is how to include a schema script on each page. Next.js automatically combines <head>
tags from all layout
or page
components into a single <head>
.
The Objective
Like any SEO-friendly website, I aim to embed a schema script in the head of every page.
A Journey Back
In the past, this task was as simple as inserting it in the <head>
section like this:
<!-- index.html -->
<head>
<script type="application/ld+json">
{
"@context": "https://schema.org",
// ... rest of the script
}
</script>
</head>
However, with the Next.js /pages
directory, it required using the dangerouslySetInnerHTML
attribute, which felt awkward but got the job done.
// 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",
// ... rest of the script
}
`}} />
</Head>
)
}
The Challenge
With the recent implementation of the /app
router, configuring metadata has become easier without directly importing <head>
using next/head
. However, using the next/head
component in the /app
router is discouraged.
This raises the question...
How can we access the <head>
for individual pages?
I hoped that the Next.js team would have addressed this by adding schema support to the new metadata
variable or creating a separate one, but no such plans seem to be in place yet.
When attempting to add a <head>
to the page
, unfortunately, it does not merge properly into the overall <head>
. One potential solution could involve adding the schema to each layout
, although having a unique layout for every page could be cumbersome.
I welcome any suggestions or ideas.