Adding schemas to the router of a Next.js 13 app is a helpful feature that can

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.

Answer №1

Official Answer from Next.js Team

To learn more about optimizing metadata using JSON-LD, you can refer to the official documentation provided by the Next.js team here. (Note that placing the schema in the <head> is not mandatory, as illustrated in the code snippet)

Implementation Example

By utilizing a JS object and incorporating a <script> tag, it becomes possible to include the JSON-LD on any desired page.

// page.tsx

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>
      {/* Embed JSON-LD into your page */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      {/* ... */}
    </section>
  )
}

Answer №2

Perhaps you already have the solution, but for those of us still searching for answers to the same issue:

import Head from 'next/head';

function ProductPage() {
  function addProductJsonLd() {
    return {
      __html: `{
      "@context": "https://schema.org/",
      "@type": "Product",
      "name": "Executive Anvil",
      "image": [
        "https://example.com/photos/1x1/photo.jpg",
        "https://example.com/photos/4x3/photo.jpg",
        "https://example.com/photos/16x9/photo.jpg"
       ],
      "description": "Sleeker than ACME's Classic Anvil, the Executive Anvil is perfect for the business traveler looking for something to drop from a height.",
      "sku": "0446310786",
      "mpn": "925872",
      "brand": {
        "@type": "Brand",
        "name": "ACME"
      },
      "review": {
        "@type": "Review",
        "reviewRating": {
          "@type": "Rating",
          "ratingValue": "4",
          "bestRating": "5"
        },
        "author": {
          "@type": "Person",
          "name": "Fred Benson"
        }
      },
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "4.4",
        "reviewCount": "89"
      },
      "offers": {
        "@type": "Offer",
        "url": "https://example.com/anvil",
        "priceCurrency": "USD",
        "price": "119.99",
        "priceValidUntil": "2020-11-20",
        "itemCondition": "https://schema.org/UsedCondition",
        "availability": "https://schema.org/InStock"
      }
    }
  `,
    };
  }
  return (
    <div>
      <Head>
        <title>My Product</title>
        <meta
          name="description"
          content="Super product with free shipping."
          key="desc"
        />
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={addProductJsonLd()}
          key="product-jsonld"
        />
      </Head>
      <h1>My Product</h1>
      <p>Super product for sale.</p>
    </div>
  );
}

export default ProductPage;

For further information, please refer to the next.js documentation on this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactions between JavaScript and PHP scripts within a web application

THE SCENARIO In the midst of creating a web application that dynamically loads content by fetching data from a MongoDB database where items and their respective authors are stored in separate collections within the same database. The author's ID is s ...

Navigating through the Express.js routes incorrectly

I currently have 3 different express.js routes set up: app.get('/packages/:name', (req, res) => {...}); app.get('/packages/search/', (req, res) => {...}); app.get('/packages/search/:name', (req, res) => {...}); At t ...

Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example: interface Inf { [key: string]: number } const obj: Inf = { '2020-01-01': 4, '2 ...

Empty the password field

<input name="e_password" id="e_password" type="password" autocomplete="off" /> The password field above is causing some trouble as it gets automatically filled in Mozilla, but not in Chrome and IE11. This seems to be retaining values from previous a ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

The Jquery ajax get method is malfunctioning

I've been trying out this code but it doesn't seem to be working. Apologies for the basic question, but I'm curious to understand why it's not functioning as expected. $(document).ready(function(){ $("button").click(function(){ ...

Tips for linking together AJAX requests with vanilla JavaScript

I have searched extensively for solutions using only plain JavaScript, but I have not been able to find a suitable answer. How can I tackle this issue with pure JavaScript given that my repetitive attempts haven't yielded any results? function ...

Is it possible to use Docxtemplater.js in a browser without familiarity with Node, Browserify, or npm?

I'm trying to get Docxtemplater.js to function properly on a browser. Unfortunately, I lack knowledge in areas such as Node.js, Browserify.js, "npm", "bower", and other technical aspects commonly found in modern JavaScript libraries. While I do inten ...

Node.js Express API returns an error status with an empty array response in a RestFul manner

Currently, I am in the process of developing a RestFull API using Node.JS to validate if a specific license plate is registered in my database (which happens to be MySQL). The endpoint that I have set up for this task is as follows: http://localhost:3009/_ ...

Troubleshooting: jQuery's append function does not seem to be functioning properly when trying

I am attempting to include a stylesheet in the head section of my page, but it seems that using 'append' is not getting the job done. Is there an alternative approach I should consider? Here is the code snippet: $('head').append(&apos ...

Tips for transferring a value from a function in ASPX to a CS file

I seem to be overlooking a small detail. I have a dropdown list (DDL) and a function in my C# file. I want to pass the 'value attribute' of a selected DDL option to my function, but I can't seem to retrieve the value attribute. I checked the ...

The server's delayed response caused the jQuery ajax request to be aborted

Encountering delayed AJAX response from the PHP server upon aborting the AJAX request. Currently utilizing the CodeIgniter framework for the server script. Javascript Code: cblcurrentRequest = $.ajax({ url: baseurl + 'Login/getChannelBra ...

NPM is currently malfunctioning and displaying the following error message: npm ERR! 404

When running npm update -g, the following error occurs: npm ERR! code E404 npm ERR! 404 Not found : default-html-example npm ERR! 404 npm ERR! 404 'default-html-example' is not in the npm registry. npm ERR! 404 You should bug the author to publi ...

Braintree drop-in feature now allows for automatic disabling of the submit button while the transaction

I've been struggling with a seemingly simple task that I just can't seem to figure out. I'm using Braintree's dropin UI and I have a submit button that I need to disable while the processing is happening, but I can't seem to find t ...

Conceal the Angular Bootstrap modal instead of shutting it down

I am utilizing Angular Bootstrap Modal to launch multiple modals, including a video player. http://angular-ui.github.io/bootstrap/#/modal My goal is to maintain the video's current position even when the modal is closed. This way, when I reopen the ...

Ensure that you call setState prior to invoking any other functions

Is there a way to ensure that the setSearchedMovie function completes before executing the fetchSearchedMovie(searchedMovie) function? const { updateMovies, searchedMovie, setSearchedMovie } = useContext(MoviesContext); const fetchMoviesList = (ev ...

Node.js tutorial: Fetching all pages of playlists from Spotify API

Currently, I am attempting to retrieve all of a user's playlists from the spotify API and display them in a selection list. The challenge lies in only being able to access 20 playlists at a time, which prompted me to create a while loop utilizing the ...

The process of altering a grid in HTML and adding color to a single square

I am facing a challenge that I can't seem to overcome. I need to create a game using HTML, CSS, and JS. The concept involves a grid where upon entering a number into a text box, a picture of a cartoon character is displayed in a square which turns gre ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...