Next.js Discord

Discord Forum

I have modified some data in my DB, but getStaticProps() isn't updating it

Unanswered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
Hello,

my Nextjs version is 13.2.1, earlier I was using SSR, now I am trying to utilize the ISR (getStaticProps()), and I have made some little changes in the DB and I am making an /pages/api call from the getStaticProps() but the updated content isn't updating when running npm run build and if I am trying npm run dev then after few mins it's reflecting but not when npm run build & npm run start

/pages/api/common/blogs/all.jsx:

// DB Config
import { connectDatabase, disconnectDatabaseConnection } from '../../../../DB/MongoDBQueries/connection'

// Queries
import { getAllDataByCondition } from '../../../../DB/MongoDBQueries/common'

// CONSTANTS
import { API_END_POINT_NOT_FOUND, DATABASE_CONNECTION_FAILED, SOMETHING_WENT_WRONG, UNSUCCESSFUL_MESSAGE } from '../../../../constants'

const handler = async (req, res) => {
  // res.setHeader('Cache-Control', 's-maxage=86400')

  let client

  try {
    client = await connectDatabase()
  } catch (error) {
    res.status(500).json({ message: DATABASE_CONNECTION_FAILED })
    throw new Error(error)
  }

  try {
    if (req.method === 'GET') {
      try {
        const blogsData = await getAllDataByCondition(client, 'blog', { isDeleted: false }, { publishedDate: -1 })

        if (blogsData) {
          return res.status(200).json({ payload: blogsData })
        }
        return res.status(400).json({ payload: UNSUCCESSFUL_MESSAGE })
      } catch (error) {
        console.log(' -----------------------------------------')
        console.log('file: all.jsx:33 ~ handler ~ error:', error)
        console.log(' -----------------------------------------')
        return res.status(500).json({ payload: SOMETHING_WENT_WRONG })
      }
    }
    return res.status(404).json({ payload: API_END_POINT_NOT_FOUND })
  } catch (error) {
    return res.status(500).json({ payload: SOMETHING_WENT_WRONG })
  } finally {
    await disconnectDatabaseConnection()
  }
}

export default handler

112 Replies

Egyptian MauOP
and below is the /pages/blogs.jsx - getStaticProps code:

export const getStaticProps = async () => {
  try {
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    console.log('resp => ', resp.data)

    return {
      props: {
        blogs: resp.data.payload,
      },
    }
  } catch (error) {
    return {
      notFound: true,
    }
  }
}
can anybody help me why it's happening this way?
Egyptian MauOP
okay!
also suppose, if I am creating/adding new blog post, the above await res.revalidate("/blogs") will add the newly add blog to the blogs page & single blog page? or I've to re-run npm run build?
then it should work
see the link above for more info, they explain it in a lot of details
@joulev see the link above for more info, they explain it in a lot of details
Egyptian MauOP
I am already on that link, but it's quite unclear for me that's why I posted here... so whenever I use await res.revalidate('path/) so I don't need to re-run the npm run build & it'll add the newly added/updated data & as well as for getStaticPaths()?
no need to rerun yes
although for getStaticPaths i'm not entirely sure
you probably need to fallback: "blocking" or something to disable 404 for non-existent routes
then return notFound for truly non existent routes in getStaticProps
then res.revalidate will probably work
but i'm not sure really – the best way to know is to just play with it
run res.revalidate("/any/path") and see if it works
Egyptian MauOP
export const getStaticPaths = async () => {
  try {
    // Fetch the dynamic data to create paths for each project
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload

    // Create an array of paths with the `slug` parameter
    const paths = blogs.rows.map(blog => {
      return { params: { slug: blog.slug } }
    })

    return {
      paths,
      fallback: false, // If fallback is set to false, any paths not returned by getStaticPaths will result in a 404 page.
    }
  } catch (error) {
    console.error('Error while generating paths:', error)
    return {
      paths: [],
      fallback: false,
    }
  }
}


this is my current /blog/[slug].js page where I am using this getStaticPaths()
@joulev
yeah
@joulev yeah
Egyptian MauOP
so total there'll be 2 revalidate call

await res.revalidate('/blogs')
await res.revalidate('/blog/new-slug-name')
yeah
@joulev yeah
Egyptian MauOP
from the Postman, 3 hours ago I've added a blog, but bymistake instead of array I passed the string, then I manipulated directly in the MongoDB, now I deleted the Dummy Blog Post, but still npm run build is throwing the error for it
any help to avoid it?
Egyptian MauOP
yes
though you can remove the .next folder to clear all cache
and try to rebuild again
Egyptian MauOP
I deleted the .next folder, then tried running npm cache clean -f
still the same error
@joulev though you can remove the .next folder to clear all cache
Egyptian MauOP
I tried running npm run dev then it's working correctly, but when I ran npm run build again the error remains same
what error?
Egyptian MauOP
this is the rror
/blog/blog-title here the /blog-title that's a new post I had added few hours ago, but it's not completely deleted from the DB
and when running npm run dev there it's working correctly
ah yeah you need to check that the blog actualy exists inside getStaticProps as well
what do your getStaticPaths and getStaticProps currently look like
Egyptian MauOP
export const getStaticProps = async context => {
  try {
    const { slug } = context.params

    const resp = await serverSideAxiosInstance.get(`/api/common/blogs/${slug}/details`)

    return {
      props: {
        blog: resp.data.payload,
      },
    }
  } catch (error) {
    return {
      notFound: true,
    }
  }
}

// Add getStaticPaths function here
export const getStaticPaths = async () => {
  try {
    // Fetch the dynamic data to create paths for each project
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload

    // Create an array of paths with the `slug` parameter
    const paths = blogs.rows.map(blog => {
      return { params: { slug: blog.slug } }
    })

    return {
      paths,
      fallback: false, // If fallback is set to false, any paths not returned by getStaticPaths will result in a 404 page.
    }
  } catch (error) {
    console.error('Error while generating paths:', error)
    return {
      paths: [],
      fallback: false,
    }
  }
}
I mean thing like this basically
// pages/blogs/[slug].tsx
import {
  GetStaticPathsResult,
  GetStaticPropsContext,
  GetStaticPropsResult,
} from "next";

export async function getStaticPaths(): Promise<GetStaticPathsResult> {
  const allBlogs = await getAllBlogs();
  return {
    paths: allBlogs.map((blog) => ({ slug: blog.slug })),
    fallback: "blocking",
  };
}

export async function getStaticProps({
  params,
}: GetStaticPropsContext): Promise<GetStaticPropsResult<{ title: string }>> {
  const blog = await getBlog(params.slug);
  if (!blog) return { notFound: true };
  return { props: { title: blog.title } };
}
Egyptian MauOP
I am not using Typescript, I am using pure JS
yeah then remove the type annotations
// pages/blogs/[slug].jsx
export async function getStaticPaths() {
  const allBlogs = await getAllBlogs();
  return {
    paths: allBlogs.map((blog) => ({ slug: blog.slug })),
    fallback: "blocking",
  };
}

export async function getStaticProps({ params }) {
  const blog = await getBlog(params.slug);
  if (!blog) return { notFound: true };
  return { props: { title: blog.title } };
}
Egyptian MauOP
still the error remains same 😢
where is blog[0].tags.map used
most likely blog[0].tags is undefined or null
Egyptian MauOP
that's the issue, the 3 blogs have tags as an array, and the 4th Dummy Blog I've added earlier it was as string later I modify directly in the DB, then I deleted it as well
but still it's stuck to it whereas in the DB it doesn't exists
@Egyptian Mau that's the issue, the 3 blogs have tags as an array, and the 4th Dummy Blog I've added earlier it was as string later I modify directly in the DB, then I deleted it as well
I deleted it as well
maybe that's why it's nullish now? maybe change it to an empty array or a valid tag array?
Egyptian MauOP
but the entire entry in the DB is deleted, not only tags but the entire Entry of that blog is deleted now
then why do you still get it in the getStaticPaths?
const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')

this part still returns the removed item
so it is buggy
check it
Egyptian MauOP
but when I am running npm run dev, both /blogs & /blog/[slug] is working correctly fine
and in npm run dev in /blog/[slug] I consoled the the following:

const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload
    console.log({ blogs })


the output I got is { blogs: { count: 3, rows: [ [Object], [Object], [Object] ] } }
so I don't think it's a buggy
Egyptian MauOP
yes
it's in /pages/api/common/blogs/all
then how does it even work during build, when the api routes are not running?
i'm quite surprised, it should say something like invalid url or fetch failed
@Egyptian Mau I didn't get you
during build, there is no dev server running, there is nothing running at localhost:3000, so how does it even work there
it's like fetch("arandomwebsitethatdontexist.com"), it shouldn't work
@joulev > serverSideAxiosInstance.get('/api/common/blogs/all') does this fetch your own api routes?
Egyptian MauOP
I've configure the Axios where I am defining the baseUrl so I don't need to pass this way
@joulev hmm. so during build, what is baseUrl?
Egyptian MauOP
https://dhavalvira.com which I've configured in next.config.js
and also, the DB remains same,
so idk what's happening here
Egyptian MauOP
yes, that's where I am wondering as well, why npm run build for ISR is not updating even when I've deleted the entry from DB & as well as deleted the .next folder
Egyptian MauOP
@joulev what to do on this?
idk what happens here so cant help, sorry
@joulev idk what happens here so cant help, sorry
Egyptian MauOP
OK, what's the benefit of using ISR instead of SSR? just small help/info on this, please
@joulev ISR has better perf compared to SSR
Egyptian MauOP
okay! and better perf then it can be more beneficial for SEO as well, I guess then, right?
Not too relevant to SEO imo, though UX is significantly enhanced
@joulev Not too relevant to SEO imo, though UX is significantly enhanced
Egyptian MauOP
I didn't get you
@Egyptian Mau I didn't get you
UX is better since perf is better
Egyptian MauOP
okay
You load a website, then if it loads instantly it is better than if it loads in 1s
Egyptian MauOP
I thought Blogs pages and all relevant with ISR will be build at build-time only, so the web page will load faster then it can help the SEO as well
Yes, SSG/ISR is ideal for blogs. Idk about this particular case though since idk why that error happens
@joulev Yes, SSG/ISR is ideal for blogs. Idk about this particular case though since idk why that error happens
Egyptian MauOP
this is first time it's encountering, also tried to delete the .next, done the npm cache clean also, now due to what to it's happening this
Egyptian MauOP
@joulev

I just tried using res.revalidate('/works'), which is using ISR, and I just tried to update it using Postman by calling my API, but the /works/ page didn't got updated as it've only getStaticProps()
Egyptian MauOP
ok
we can't use http://localhost:3000 in ISR/SSR, right? @joulev
@Egyptian Mau ping
shhhhh is this site of yours open source
@joulev shhhhh is this site of yours open source
Egyptian MauOP
means? 🤔
basically move the logic from your api routes to inside getstaticprops/getserversideprops
@Egyptian Mau means? 🤔
if it is open source then i can give you an example
based on your code
cuz idk how to explain it either
Egyptian MauOP
actually I am using pure MongoDB, so I've to make connection first and then fetch the data
@joulev cuz idk how to explain it either
Egyptian MauOP
I got the issue, it seems that my Chrome Browser still have the cache, because https://dhavalvira.com/api/common/blogs/all this when I am accessing it from my Chrome, I'm still having that data, and to cross verify I checked in my Mobile, but it's not there, but it's weird thing for me
Egyptian MauOP
res.setHeader('Cache-Control', 's-maxage=86400')

this line is there in /pages/common/blogs/all API End Point
@joulev
no let's just put it this way. i have zero idea what is happening, and from the information you provided i cannot see anything of worth to tell you, so i cannot help you here. sorry about that