I created this NextJs blog, using Contentful as CMS. I found things that i should have remembered, but i forgot. This is a note to remind myself How NextJs and Contentful work with each other. Also, there's a little bit about Algolia.
NextJS and Fetch caching
NextJs caches request. We know this. Now, how do we use this to our advantage? One, is to revalidate requests every some period of time. The second one, is to use request tag and webhook. Let's see how they can help us.
Revalidate Each Request
One way, is to revalidate all request with a sane period of time. Say 15 minutes? To do that, we can configure the fetch function. For example:
That should do it. It will be enough for most blog. But what if i have more time to do this? Ideally, i want each cache to be revalidated after the content have been updated, that should remove unnecessary calls to Contentful. That's where tag
comes in
Adding Tag To Each Request and Using Webhook
Instead of using time to revalidate our request, we can use tag(s) for each request. and revalidate them when things are updated.
Next, in our webhook, we can revalidate the tag. So the in next call, it will actually make the request.
I think this is a better option, NextJs will cache all our request, and we can remove the cache whenever we need it. This is called On Demand Revalidation. The request will hit Contentful's server after we revalidate the tag.
Now, to handle the webhook from Contentful, we need to create the handler on NextJs. Checkout this example POST handler in NextJs:
Sometimes, Contentful only sends us partial data: not containing fields
and metadata
keys. I'm only seeing this when i update the post status to unpublish. But i'll get the data from Post and Draft that way, so i can sleep easy.
The request getPostById
and getDraftById
should not be cached. We can use { cache: 'no-store' }
for this.
Don't forget to use a secret. We don't want anyone to be able to do this to our blog.
Contentful's Webhook to NextJS
Setting up Webhook in Contentful is easy. Go to "webhook" in the settings menu:
Setup the name, URL, and Configure the triggers to only send events for Autosave
, Publish
and Unpublish
on the Entry row. Like this:
In the Header
section, set the secret header however you like:
That's it.
Contentful's Webhook to Algolia
In the webhook to algolia, only send the data you want the user to search. Sending the whole data will cause errror from Algolia, saying the data is too big. Checkout this example payload:
To bad we can't have the metadata
field to only show the tag content. Set it up in the payload section:
In case you're wondering, why is it dark? I'm using Firefox, with the UltimaDark extension.