An error occurred in NextJS because the property 'title' is being read from an undefined value, resulting in a

I've encountered a problem while trying to deploy my blog app to production. Everything was working fine in the development environment, but now I'm facing this error:

Error occurred prerendering page "/blogs/[slug]". Read more: https://nextjs.org/docs/messages/prerender-error TypeError: Cannot read property 'title' of undefined

I'm puzzled because the app was functioning properly before. It seems like the issue lies in this part of the code:

import Head from "next/head";
import "bootstrap/dist/css/bootstrap.min.css";
import ReactMarkdown from "react-markdown";
import moment from "moment";

const Post = ({ posts }) => {
  return (
    <>
      <Head>
        <title>{posts && posts.title}</title>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0"
        ></meta>
      </Head>
      <div className="container" style={{ marginTop: "3.85rem" }}>
        <div className="row">
          <h1>{posts.title}</h1>
        </div>
        <div className="row d-flex justify-content-end">
          <p style={{ textAlign: "right" }}>
            {moment(posts.dateTime).format("dddd, Do MMMM YYYY, hh:mm:ss a")}
          </p>
        </div>
        <br />
        <div className="row d-flex justify-content-center">
          <img
            className="postThumbNail"
            src={posts.thumbnail.url}
            alt={posts.thumbnail.url}
          />
        </div>
        <br />
        <ReactMarkdown>{posts.body}</ReactMarkdown>
      </div>
    </>
  );
};

export async function getStaticProps({ params: { slug } }) {
  const res = await fetch(
    `https://someapi.com/blogs?slug=${slug}`
  );
  const blogPost = await res.json();

  return {
    props: {
      posts: blogPost[0],
    },
    revalidate: 600,
  };
}

export async function getStaticPaths() {
  // Get Post From Strapi
  const res = await fetch(
    "https://someapi.com/blogs"
  );
  const post = await res.json();
  //  Retrun Enrich Content
  return {
    paths: post.map((posts) => ({
      params: { slug: String(posts.slug) },
    })),
    fallback: true,
  };
}

export default Post;

Answer №1

Approach 1 Prior to accessing the attribute, it's important to verify its existence using optional chaining :

  <h1>{data?.title}</h1>

Approach 2 Alternatively, return null if the object is null and wait for the data to load:

if(!data) return null

return <div> ...Your Code </div>

Answer №2

The reason for this issue arises from the use of fallback: true in the getStaticPaths method without properly handling the fallback page served by Next.js before getStaticProps completes its execution. This results in empty props being passed to the page component.

In the “fallback” scenario of a page:

  • The page's props will be empty.
  • By utilizing the router, you can identify if the fallback is being rendered; router.isFallback will be true.

Next.js, Fallback Pages documentation


#1 Managing the fallback page with router.isFallback

You can appropriately handle the fallback version of the page by utilizing router.isFallback.

const Post = ({ posts }) => {
    const router = useRouter()

    // Show loading until `getStaticProps()` completes, and provides the props.
    if (router.isFallback) {
        return <div>Loading...</div>
    }

    return (
        <h1>{posts.title}</h1>
    );
};

#2 Opt for fallback: 'blocking' as an alternative

If you do not actually require the fallback feature, you can switch the fallback value in getStaticPaths to fallback: 'blocking'. This will create new pages similarly to fallback: true, but will delay rendering until getStaticProps has executed.

export async function getStaticPaths() {
    const res = await fetch("https://someapi.com/blogs");
    const post = await res.json();

    return {
        paths: post.map((posts) => ({
            params: { slug: String(posts.slug) }
        })),
        fallback: 'blocking'
    };
}

Answer №3

    <Header>
        <title>{posts && posts.title}</title>
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0"
        ></meta>
      </Header>
      <div className="container" style={{ marginTop: "3.85rem" }}>
        <div className="row">
          <h1>{posts && posts.title}</h1> // Don't forget to check if posts actually exist
        </div>
        <div className="row d-flex justify-content-end">
          <p style={{ textAlign: "right" }}>
            {moment(posts.dateTime).format("dddd, Do MMMM YYYY, hh:mm:ss a")}
          </p>
        </div>
        <br />
        <div className="row d-flex justify-content-center">
          <img
            className="postThumbNail"
            src={posts.thumbnail.url}
            alt={posts.thumbnail.url}
          />
        </div>
        <br />
        <ReactMarkdown>{posts && posts.body}</ReactMarkdown>
      </div>

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

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

"Creating a custom input tag in Rails that triggers an event when the value is changed

Is there a more efficient way to trigger events when the value of an input tag changes (i.e., whenever a character is entered or deleted) and display these values in the controller without relying on ajax? Currently, my approach involves implementing a Ja ...

The data provided must be in the form of an EventTarget

Currently, I am using the latest version of nextjs along with the App Router. My goal is to fetch data from my next API located at the /api endpoint. However, I keep encountering a frustrating error 500. Error [ERR_INTERNAL_ASSERTION]: TypeError [ERR_INV ...

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Incorporate Material Design Lite and AMP into your Angular 5 project for a sleek

Looking to develop an e-commerce progressive web app using angular 5. Wondering how to incorporate AMP with angular 5 in Google Material Design Lite. If not viable, what are some alternative options worth considering? ...

Transforming a Multi-Dimensional Array into an HTML Table

Experimenting with a new idea. I hope the solution is straightforward; I just can't seem to figure it out. Imagine I have an array like this: var items = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]; My goal is to rearrange the data so that it looks like t ...

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...

The library 'material-ui' does not have a 'withStyles' export available

Here is the content of my package.json file. Everything was working fine until recently when I started encountering this error. "@material-ui/icons": "1.0.0-beta.42", "chartist": "0.10.1", "classnames": "2.2.5", "material-ui": "1.0.0-beta.41", "npm-ru ...

Tips for leveraging a button to trigger server-side actions

Being a novice in web development, I'm currently working on a straightforward website that enables users to download files from the server side. These files are not pre-created; instead, there will be a button on the HTML page. When a user clicks this ...

Is there a way to adjust the width of the info panel in an SVG to automatically match the width of the SVG itself?

I am looking to place the information panel at the bottom of my SVG map and have it adjust its width according to the width specified in the viewBox. This way, even if I resize the map, the info panel will automatically adjust to fill completely based on t ...

Unable to get HTML text input validation with RegEx to function, despite incorporating the required attribute

I am attempting to create dynamically generated text inputs that only allow for digits and an optional decimal point. I have added the required attribute but the inputs are not responding to the RegEx pattern. var howMuch = $("<input>").attr("type", ...

Stop clicks from interfering with dragging in three.js

My GLTF model in Three.js has objects within it, and I want the camera to zoom in on an object when the user clicks on it. However, I am facing an issue where if the user drags after clicking on an object, a click is triggered upon releasing the mouse butt ...

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

Accessing a webpage solely by logging in prevents unauthorized access

My login page currently redirects to a page named gallery.html upon successful login. However, I have noticed that entering /gallery.html in the URL also directly accesses the secure page without logging in. Can anyone suggest an effective way to impleme ...

Creating a User-friendly Layout for Admin Pages in Next.js Version 13

Hey there, I'm facing an issue with the layout while using Next.js 13 Experimental App Directory. On my website's index page or routes '/', I want to show a landing page and use a specific layout for all pages except for those under the ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

The ng-view in index.html is not being loaded by AngularJS

I've been working on setting up a single-page application using AngularJS. In my setup, I'm using Node with Express and have an Apache server functioning as middleware. The issue I'm facing is that while my index.html page loads without any ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly. #hi{ background-color: blue; width: 2px; height: 10px; position: absolu ...