I have modified some data in my DB, but getStaticProps() isn't updating it
Unanswered
Egyptian Mau posted this in #help-forum
Egyptian MauOP
Hello,
my Nextjs version is 13.2.1, earlier I was using SSR, now I am trying to utilize the ISR (
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 handler112 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 Mau and below is the `/pages/blogs.jsx` - getStaticProps code:
js
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,
}
}
}
after updating the db you need to revalidate the
/blogs page https://nextjs.org/docs/pages/building-your-application/rendering/incremental-static-regeneration#on-demand-revalidationin the api route where you update the db, or in any api routes basically,
await res.revalidate("/blogs")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?@Egyptian Mau 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`?
basically if you need to revalidate a page at
/any/path you just call res.revalidate("/any/path")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 routesthen return
notFound for truly non existent routes in getStaticPropsthen
res.revalidate will probably workbut 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 worksEgyptian 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
@Egyptian Mau js
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()`
uhm. now build the app, then add a post to the db, then try to res.revalidate("/blogs/the-new-post"), does it work?
if it doesn't work, use
fallback: "blocking" and it should probably work@joulev uhm. now build the app, then add a post to the db, then try to res.revalidate("/blogs/the-new-post"), does it work?
Egyptian MauOP
/blog/new-blog-slug?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 itany help to avoid it?
@Egyptian Mau 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
weird... are you sure your database is now correct?
if db is correct then npm run build shouldnt complain
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 -fstill 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 samewhat 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 DBand when running
npm run dev there it's working correctlyah 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,
}
}
}@joulev ah yeah you need to check that the blog actualy exists inside getStaticProps as well
Egyptian MauOP
how to do that?
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 wellmaybe 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
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 fineand in
the output I got is
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 Mau and in `npm run dev` in `/blog/[slug]` I consoled the the following:
js
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] ] } }`
serverSideAxiosInstance.get('/api/common/blogs/all')does this fetch your own api routes?
Egyptian MauOP
yes
it's in
/pages/api/common/blogs/allthen 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
@joulev then how does it even work during build, when the api routes are not running?
Egyptian MauOP
I didn't get you
@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@Egyptian Mau I've configure the Axios where I am defining the `baseUrl` so I don't need to pass this way
hmm. so during build, what is baseUrl?
@joulev hmm. so during build, what is baseUrl?
Egyptian MauOP
https://dhavalvira.com which I've configured in next.config.jsand 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 folderEgyptian 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
@Egyptian Mau OK, what's the benefit of using ISR instead of SSR? just small help/info on this, please
ISR has better perf compared to SSR
@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 thisEgyptian MauOP
@joulev
I just tried using
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 Mau <@484037068239142956>
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()`
Everything about your code is just weird idk what’s happening in there anymore so i cant help, sorry
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 meEgyptian 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
@Egyptian Mau 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
maybe in my local it's cached, as I checked in my Mobile, the deleted MongoDB Object isn't coming in this