See Sanity in action 👀 Join us for a live product demo + Q&A →

How to tackle the "Cannot read properties of null" error during build time in a Next.js project

7 replies
Last updated: Feb 19, 2023
Hello fellow devs, upon doing either npm run build or yarn build i have come across this error, Cannot read properties of null (reading 'mainImage'). How can I tackle this issue? I would appreciate any form of help. Thank you. Ill be attaching the screenshots. First one is page.tsx at '*[project]/app/(user)/post/[slug]/page.tsx*', the error originated from line 53. Second one is post.tsx at '*[project]/schemas/post.ts*', where the type of the field is defined. Third image provides an high level view of the project along with the caught error message in the terminal.
Feb 19, 2023, 10:17 AM
There is data in mainImage. just checked by querying
Feb 19, 2023, 10:42 AM
From what I understand, you are exporting async function as component ? You should instead export a component and use async hook :
export function Post(props) {
    const post = usePost(props.slug); // <- async function
    if(post) {
       return null // <- or loader
    return (
        //<- JSX of your component
Feb 19, 2023, 11:21 AM
Cannot read properties of null (reading 'mainImage')
Indicates that you are trying accessing
not that
is null
Feb 19, 2023, 11:23 AM
user Q
thanks for replying. Ive been trying to implement your suggested solution but i think i a going wrong somewhere syntactically. I am relatively new to typescript, nextjs and sanity.
Feb 19, 2023, 9:02 PM
i am facing this issue during build time ie when i do npm run build or yarn build otherwise this application is working fine on my locacl server
Feb 19, 2023, 9:02 PM
is there any other approach that i could try
Feb 19, 2023, 9:08 PM
actually your solution worked just had to add this line if (!post){ return null;
Feb 19, 2023, 10:09 PM – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in