Table of contents not working on Vercel, yet functions properly on localhost

I'm struggling to incorporate a dynamic table of contents into my blog page on next.js. The code functions perfectly on my local server, but upon deploying it to Vercel, I encounter the following error:

TypeError: Cannot read properties of undefined (reading 'content')
at BlogPost (/vercel/path0/.next/server/pages/posts/[slug].js:111:23)
at Jc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:64:191)
at Mc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:66:253)
at Z (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:71:89)
at Nc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:73:98)
at Mc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:67:131)
at Z (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:71:89)
at Mc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:70:13)
at Z (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:71:89)
at Nc (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.browser.production.min.js:73:98)

Upon investigation, I discovered that the build failure is triggered by the .processSync command on line 85 (as indicated in my comment). Unfortunately, resolving this issue has been beyond my capability... Any insights or assistance as to why this occurs would be greatly appreciated.

Here's the complete source code: (I've omitted the grahpcms route when setting up the GraphQLClient for security reasons, so that's not the cause of failure here.)

import { GraphQLClient, gql } from "graphql-request";
import { useRouter } from "next/router";
import { unified } from "unified";
import rehypeParse from "rehype-parse/lib";
import rehypeStringify from "rehype-stringify/lib";
import { visit } from "unist-util-visit";
import parameterize from "parameterize";

const graphcms = new GraphQLClient();

const QUERY = gql`
  query Post($slug: String!) {
    post(where: { slug: $slug }) {
      title
      id
      content {
        html
      }
      datePublish
      coverPhoto {
        url
      }
      datePublish
    }
  }
`;

const SLUGLIST = gql`
  {
    posts {
      slug
    }
  }
`;

export async function getStaticPaths() {
  const { posts } = await graphcms.request(SLUGLIST);
  return {
    paths: posts.map((post) => ({ params: { slug: post.slug } })),
    fallback: true,
  };
}

export async function getStaticProps({ params }) {
  const slug = params.slug;
  const data = await graphcms.request(QUERY, { slug });
  const post = data.post;
  return {
    props: {
      post,
    },
  };
}

export default function BlogPost({ post }) {
  const router = useRouter();

  var toc = [];

  //Forms the HTML String into a tree that we can add logic too
  //Then forms that tree back into html string
  const newContent = unified()
    .use(rehypeParse, {
      fragment: true,
    })
    .use(() => {
      return (tree) => {
        visit(tree, "element", (node) => {
          if (node.tagName === "h2") {
            const id = parameterize(node.children[0].value);
            node.properties.id = id;
            toc.push({
              id: node.properties.id,
              title: node.children[0].value,
            });
            console.log("id", id);
          }
        });
      };
    })
    .use(rehypeStringify)
    //THIS IS WHERE THE DELPLOYMENT FAILS
    .processSync(post.content.html)
    .toString();

  if (router.isFallback) {
    return <h2>Loading</h2>;
  }

  return (
    <div>
      <header>
        <h1>{post.title}</h1>
        <img
          src={post.coverPhoto.url}
          width="100%"
          style={{ borderRadius: "1rem" }}></img>
        <span>Published: {post.datePublish}</span>
      </header>
      <main>
        <div>
          {toc.map(({ id, title }) => {
            return (
              <li style={{ listStyle: "none" }} key={id}>
                <a style={{ fontSize: "1.1rem" }} href={`#${id}`}>
                  <b> {title}</b>
                </a>
              </li>
            );
          })}
        </div>
        <div
          className="blogpost"
          dangerouslySetInnerHTML={{ __html: newContent }}
        />
      </main>
    </div>
  );
}

Your assistance will be highly appreciated!

Answer №1

To handle undefined props, you can utilize the optional chaining operator like so:

post?.content?.html

Another step to consider is running the project on your local machine instead of relying on Vercel for building and catching any additional errors.

By using an if statement, you can manage undefined props effectively - just remember to position it before the main return statement and after all hooks in your code.

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

How can you show images in Nextjs using a browser if they are not saved in the /public folder?

In my current project, I am utilizing Next.js as a full-stack framework with API route handlers in the backend. One issue I have encountered is related to storing images under the /uploads directory using the fs.writeFile method and only saving the path to ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

I discovered that the Next Router was not properly mounted in the electron-powered Next app I had developed

I have developed an npm package using Next.js and TypeScript to share a report module from my online application to my offline application. I created a simple page with a Link tag for routing when clicking a button, and the sharing of this simple page work ...

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

Obtain image URL from object properties using AngularJS

Just starting out with Angular JS and I have a question. I'm currently working on a project and I have a solution in mind, but I was wondering if there's a more "angular-esque" approach that I could take. The idea is for each videoid, there wou ...

What is the best way to retrieve the value of a JavaScript variable and display it within an HTML label tag

In my JavaScript code, I'm attempting to retrieve location coordinates using the onchange event and then display those coordinates in a label. I've tried alerting the coordinates successfully, but I'm struggling to update the label using doc ...

Puzzled by the specialized link feature

As I delve into the world of React and Next.js, I find myself working on the link component. Initially, I had a grasp on basic routing in next.js which seemed pretty straightforward. However, things took a confusing turn when I stumbled upon this code: imp ...

Creating stunning visuals with the power of SVG

I need to create a graphics editor similar to Paint using SVG for a school project. I have JavaScript code for drawing shapes like circles and lines, but when I try to add them to an onClick function for a button, it doesn't seem to be working. funct ...

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

What is causing the UI to change every time I add a tag to refresh the web view?

Recently, I added a pull-to-refresh feature to my React Native webview app using the react-native-pull-to-refresh library. After implementing the tag, I noticed that the UI got rearranged with the webview shifted down and the top half occupied by the pull- ...

Verify if the input field is devoid of any content or not

I am planning to create a validation form using Vanilla JavaScript. However, I have encountered an issue. Specifically, I want to validate the 'entername' field first. If the user does not enter any letters in it, I would like to display the mess ...

Extract JSON data from a web address using JavaScript

A unique system has been created to parse JSON and style it using CSS. Instead of outputting the data within the script, the goal is to retrieve data from a local or remote URL. <script type='text/javascript'> $(window).load(function(){ va ...

What could be causing the CSS transition to fail when the menu button is clicked?

After clicking on the menu, a class 'active' is added to both the 'div' and 'section' elements. https://i.stack.imgur.com/jbamR.png The following javascript code accomplishes the above functionality: <script> const ...

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

Trigger Function on Input Change in Angular 2

Key aspects of component nesting: export class Child { @Input() public value: string; public childFunction(){...} } Main component responsibilities: export class Parent { public value2: string; function1(){ value2 = "a" } function2( ...

The icon displays correctly in Firefox but is not visible in IE

link REL="SHORTCUT ICON" HREF="/images/greenTheme/favicon.ico" type="image/x-icon" While this code functions properly in Firefox, it appears to be causing issues in Internet Explorer. Can anyone provide guidance on how to resolve the compatibility issue w ...

Unlocking the Controller Action: Navigating from a Component Controller in Ember

I am currently trying to enhance the functionality of an Ember component. The specific component I am working on is located here: app / templates / programmers.hbs {{echo-hlabel-tf id= "id-test-hlabel" class="class-test-hlabel-mio" label="Horiz ...

Struggling to fix errors within a nested div element?

I'm currently utilizing AngularJS to perform basic form validation. Below is the current code snippet: <form name="myForm" id="form_id" method="post" novalidate> <div class="form-group"> <label for="myField_input" class="c ...

Are third-party scripts and HTML widgets able to replicate your website's data, including cookies, HTML, and other elements?

Currently, I am in the process of constructing a website that incorporates a third-party weather HTML widget. The widget is sourced from a trusted and reliable source on the web. It consists of a link and small JavaScript tags that are executed once loaded ...

Troubleshooting issue: EJS loop not functioning correctly when handling JSON information

Having an issue with looping in an EJS file. Here's the data I'm working with: { "name": "Marina Silva", "info": [{ "periodBegins": "Sun Apr 14 23:48:36 +0000 2011", "periodFinishes": "Sun Apr 7 23:48:36 +0000 201 ...