← All writing

· 2 min read

Why a freshly published page returned a 404 once

Publishing through the API left the new page missing for one request. The cause was revalidateTag with the max profile, and the fix is an expiry of zero.

After a project was published through this site's API, its page returned a 404 on the first request, and the projects index did not list it. A few seconds later both were correct. This post explains why, and what changed.

How the site caches content

The public pages read posts and projects through functions marked with use cache, each tagged with a name such as posts or projects. The admin lists have their own tags, admin-posts and admin-projects. When content changes, the code invalidates the tag and the next request rebuilds the cached result.

Two ways to invalidate

Next.js 16 has two functions for this. updateTag expires the tag immediately, so the very next request sees the change. It only works inside a Server Action, which is how the admin editor saves content, so the editor always sees its own edits.

The token API runs in route handlers, where updateTag is not available. Those handlers called revalidateTag(tag, "max"). With the max profile, the old content is served while the new content is built in the background. That is a fine default for pages that can be a moment out of date, and it is the reason for the 404. The first request after the publish was the stale one.

The fix

The Next.js docs name the alternative for this exact case. Passing { expire: 0 } as the second argument means stale content is never served, so the next request waits for a fresh result. The API routes for posts, projects, messages, API tokens and the excluded IP list now use it.

Two places keep max on purpose. The contact form revalidates the inbox in the background, because the visitor who sent the message never reads it. And the timestamp that records when an API token was last used runs on authenticated requests, at most once a minute per token, so waiting on it would only slow every call down.

What it costs

An expiry of zero makes the next public request after a write wait on the database instead of getting a cached page. API writes are rare and rate limited per token, so the cost is small.