Reputation: 827
Currently I'm using getStaticProps
and getStaticPaths
to prerender the latest X number of articles before my site goes live. This works great, but if a new article is created and shown on the front page while the site is still running, the new article returns a 404 page.
What I'd like is if a page doesn't exist, the id (like mysite.com/posts/id in the /posts/[id].js
file) is passed to a function so that the page can be prerendered on the server during runtime. I don't want to default to getServerSideProps
, since that would render the page on every request, what I'm looking for is to permanently render the page, and save it as a crawlable file just like getStaticProps
does, only during runtime.
TL:DR I'm looking for a getStaticPaths
/getStaticProps
behavior during runtime. Is this possible in NextJS?
If not, how could I have new articles readily available without having to take down the server, build it again, and start it up again every so often, which seems horribly unmanageable.
Upvotes: 2
Views: 2598
Reputation: 827
It seems the answer was simpler than I thought. Within getStaticPaths, you just need to set fallback: true, then within the function component add some fallback content that viewer will see temporarily while the server renders the new page and sends it back. Example [id].js:
export default function Post({ postProps}) {
const router = useRouter()
if (router.isFallback) {
return <div>Loading...</div>
}
return (
...
)
}
This will allow the server to use getStaticProps
on the new ID and render the new page, while the client sees Loading...
then once rendering is complete, the client is given the new page. This render only needs to happen once for new pages and will be readily available for any subsequent views or SEO crawlers.
Upvotes: 3
Reputation: 19762
TL:DR I'm looking for a getStaticPaths/getStaticProps behavior during runtime. Is this possible in NextJS?
Yes and no. There's a revalidate option which, as of now, requires a client-side request to invalidate stale data. Then another client-side request must be made to retrieve the updated data. This has the unavoidable consequence of User A seeing stale data (triggering the revalidation) and User B seeing the up-to-date data. As of yet, there's no way to programmatically trigger a revalidation upon a CRUD (CREATE, READ, UPDATE, DELETE) event.
A (not recommended) workaround is to manually trigger a client-side request immediately after a CRUD event. This way, in theory, User A and User B should always see up-to-date data. Unfortunately, this means longer response times for CRUD operations.
In short, right now getServerSideProps
is the only available option to guarantee 100% up-to-date data for SEO indexing. Otherwise, if you don't care for SEO indexing, then client-side requests should suffice.
Upvotes: 5