So I am working on a simple next js application A Blog System. So like a basic blog, I have a posts section where I see all my posts that i have ever posted.
The post page is a dynamic route named
/posts/title-of-the-post
So i used a getStaticPaths
and getStaticProps
for extracting the title and fetching the data from the mongodb database. It is all working great.
But I have another route called
/posts/add-new
that adds a new post to my database and my readers can see these. So the function is working and when I create a new post it is saved in the database but when I try to access it with url of posts/new-post-url
I get 404 Not Found error.
I can pretty much understand that the dynamic pages and paths are build on runtime so when I add a new page, it is not in the build folder so 404.
But how to solve it. What I want is the ability to add new pages in my blog and they should be SEO friendly and visible to user. Just like how I posted this question on stack overflow and it will now be accessible by the url and after some time it will take the top spot in google search.
Please help. Thank YOu in advance π -> π -> π
2
Answers
To get the fresh data, set
revalidate:1
ingetStaticProps
andfallback:true
ingetStaticPaths
. Check the example belowIn your component, if
fallback:true
Next.JS provides 3 options for serving content.
SSG Static Site Generator – it builds pages once and serves pregenerated content.
ISG Incremental Static Regeneration – it allows you to regenerate static pages under certain conditions.
SSR Server Side Rendering – server will generate a page per request.
For blog SSG would be the better choice: posts usually donβt change or changes rarely.
You should use the
fallback
setting ingetStaticPaths
. You have to setfallback
totrue
or'blocking'
.true
– the new paths will serve as a fallback on the first request, while Next.JS will be generating the page. Then it will swap the fallback to the actual content.'blocking'
– the new paths will be blocked until the page is generated.For both options, all subsequent requests will serve the pre-generated page.
Keep in my for long building pages you can get a timeout error. By default, itβs 60 seconds, but you always can tune it by
staticPageGenerationTimeout
.