Next.js blog site deployment to Vercel failing with "Cannot read properties of undefined" error

7 replies
Last updated: Nov 13, 2022
Hi I followed this tutorial to make a nextjs blog site and it works perfectly locally, i can see my blog post, but when i deploy it to vercel and deploy sanity studio and add the cors allowance for everything, i am only getting vercel build failures.

https://www.sanity.io/blog/build-your-own-blog-with-sanity-and-next-js
My code is exactly the same as in that blog post, is it because i am using a custom domain?


info  - Generating static pages (0/138)
Error occurred prerendering page "/post/[slug]". Read more: <https://nextjs.org/docs/messages/prerender-error>
TypeError: Cannot read properties of undefined (reading 'title')
    at Post (/vercel/path0/.next/server/pages/post/[slug].js:70:5)
    at d (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
    at bb (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
    at a.b.render (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
    at a.b.read (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
    at Object.exports.renderToString (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
    at Object.renderPage (/vercel/path0/node_modules/next/dist/server/render.js:736:46)
    at Function.getInitialProps (/vercel/path0/.next/server/chunks/859.js:618:16)
    at Object.loadGetInitialProps (/vercel/path0/node_modules/next/dist/shared/lib/utils.js:69:29)
AI Update

The error you're seeing is a classic Next.js static generation issue. During build time on Vercel, your getStaticPaths generates paths for blog posts, but getStaticProps isn't returning the post data properly, so your component receives undefined instead of a post object with a title property.

This is NOT related to your custom domain or CORS settings - those would cause runtime errors, not build failures. The issue is that your component is trying to access post.title when post is undefined.

The Root Cause

Looking at your code, you have fallback: true in getStaticPaths. This means Next.js will try to generate pages for slugs that weren't pre-rendered at build time. However, when fallback: true is used, the component can receive undefined props during the initial render.

Solutions

1. Add a Loading State for Fallback Pages

When using fallback: true, you need to handle the case where the post hasn't loaded yet:

import { useRouter } from 'next/router'

const Post = ({post}) => {
  const router = useRouter()
  
  // Add this check for fallback pages
  if (router.isFallback) {
    return <div>Loading...</div>
  }
  
  // Add a safety check in case post is still undefined
  if (!post) {
    return <div>Post not found</div>
  }

  const {
    title = 'Missing title',
    name = 'Missing name',
    categories,
    mainImage,
    authorImage,
    body = []
  } = post
  
  // rest of your component...
}

2. Use fallback: false or fallback: 'blocking'

If you want all posts generated at build time, change your getStaticPaths:

export async function getStaticPaths() {
  const paths = await client.fetch(
    groq`*[_type == "post" && defined(slug.current)][].slug.current`
  )

  return {
    paths: paths.map((slug) => ({params: {slug}})),
    fallback: false, // or 'blocking'
  }
}
  • fallback: false = 404 for any path not returned by getStaticPaths
  • fallback: 'blocking' = server-render on first request without showing a fallback

3. Add Error Handling in getStaticProps

export async function getStaticProps(context) {
  const { slug = "" } = context.params
  const post = await client.fetch(query, { slug })
  
  // Return 404 if post doesn't exist
  if (!post) {
    return {
      notFound: true,
    }
  }
  
  return {
    props: {
      post
    }
  }
}

4. Check Your Environment Variables

The most common cause of this working locally but failing on Vercel is missing environment variables. Make sure you've added these in your Vercel project settings (Settings → Environment Variables):

  • NEXT_PUBLIC_SANITY_PROJECT_ID
  • NEXT_PUBLIC_SANITY_DATASET
  • SANITY_API_TOKEN (if using authenticated requests)

Add them for all environments (Production, Preview, Development).

5. Ensure Your Sanity Client is Configured Correctly

Make sure your client uses useCdn: false for build-time queries and includes an API version:

const client = createClient({
  projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
  dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
  apiVersion: '2023-05-03', // use a specific date
  useCdn: false, // important for build time
})

Setting useCdn: false ensures you're getting the latest data during builds, which is important for static generation.

Why It Eventually Worked

You mentioned it worked after redeploying 3 times - this often happens when:

  • Environment variables took a moment to propagate
  • Vercel's cache needed clearing
  • The Sanity CDN cache synchronized

This is a common issue in the community. The typical culprits are environment variables and missing fallback handling.

The best long-term fix is implementing options #1, #2, and #3 above to make your code more resilient. This way, even if something goes wrong during the build, your app will handle it gracefully instead of crashing with the "Cannot read properties of undefined" error.

my slug page
// [slug].js
import groq from 'groq'
import imageUrlBuilder from '@sanity/image-url'
import { PortableText } from '@portabletext/react'
import client from '../../utils/client'

import { Meta } from '../../layout/Meta';
import { AppConfig } from '../../utils/AppConfig';
import { NavBar } from '../../templates/NavBar';

function urlFor (source) {
  return imageUrlBuilder(client).image(source)
}

const Post = ({post}) => {
  const {
    title = 'Missing title',
    name = 'Missing name',
    categories,
    mainImage,
    authorImage,
    body = []
  } = post
  return (
    <article className='text-xl center'>
      <Meta title={AppConfig.title} description={AppConfig.description} />
      <NavBar />
    
      <h1 className='text-6xl'>{title}</h1>
      <br></br>
      {categories && (
        <ul>
          Posted in
          {categories.map(category => <li key={category}>{category}</li>)}
        </ul>
      )}
      { (
        <div>
          <img
            src={urlFor(mainImage)
              .width(500)
              .url()}
            alt={`${name}'s picture`}
          />
        </div>
      )}
      <br></br>
      {<PortableText
      className={'white-space: pre-line grid gap-14 md:gap-22 lg:gap-24 '}
        value={body}
      />}
    </article>
  )
}

const query = groq`*[_type == "post" && slug.current == $slug][0]{
  title,
  "name": author->name,
  "categories": categories[]->title,
  "authorImage": author->image,
  "mainImage": mainImage,
  body
}`
export async function getStaticPaths() {
  const paths = await client.fetch(
    groq`*[_type == "post" && defined(slug.current)][].slug.current`
  )

  return {
    paths: paths.map((slug) => ({params: {slug}})),
    fallback: true,
  }
}

export async function getStaticProps(context) {
  // It's important to default the slug so that it doesn't return "undefined"
  const { slug = "" } = context.params
  const post = await client.fetch(query, { slug })
  return {
    props: {
      post
    }
  }
}
export default Post
What’s the build error you are getting at vercel?
the build error is in the first log:
Error occurred prerendering page "/post/[slug]". Read more: <https://nextjs.org/docs/messages/prerender-error>
TypeError: Cannot read properties of undefined (reading 'title')

(curious about the answer, subscribing to thread) 👀
user C
any ideas? Not sure why title is not being found on vercel I feel like with all the CORS origins I added it probably isn't an issue with vercel not being able to connect to sanity?
user A
if CORS is good to go typically the next culprit are the variables at Vercel. Here’s a few more things to check:
• If you have localHost specified in your project
• If your build command isn’t correct. at Vercel
• In the event you are using variables, that they match
• That you are using the same version of NPM both locally and on Vercel
Wow I redeployed 3 times out of frustration and all of a sudden its working now.. my nextjs projects might be cursed lmao... Thankyou!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?