Next.js Cache Gotcha
This one is a sneaky one, and caching is becoming synonymous with annoying. But that aside, here's the scenario.
I'm working on the gift giving application. The use case is someone purchases a gift and that action triggers:
- the generation of a voucher code.
- the creation of a transaction object that stores the transaction information in the databases and associates the generated gift code with the transaction before sending the user an email with their gift code.
Locally it works just fine, but when deployed, it works then it breaks.
I think I just figured out why. Caching.
looking at the vercel logs dashboard, I noticed that the cache option registered a hit and the status code was 304 (not modified), indicating that the request I'm making hasn't changed since the last time I made it.
Looking at the documentation, it becomes clearer what the issue might be? Turns out, according to the docs, Route Handlers are cached by default when using the GET
method with the Response
object.
So I have to opt out of caching to disable that. I'll be using a segment config option to do that:
// Opt out of caching for all data requests in the route segment
export const dynamic = 'force-dynamic'
That seems to have solved my problems. Huzah! And with that folks, we've learnt something new about Next.js Route Handlers.
But as we know these things typically have lives of their own, let's sleep on it then come back tomorrow and see if it's still functional after being slept on.