Why can't I run updateTag in a route handler?
This post might have stale content, as canary is 4837 commits ahead.
why can't i run updateTag within a route handler?
Perfect! Now I have the answer. Let me explain why updateTag can't be run within a route handler:
##Why updateTag Can't Run in Route Handlers
updateTag is restricted to Server Actions only and will throw an error if called from a route handler.
###The Technical Reason
Looking at the source code in packages/next/src/server/web/spec-extension/revalidate.ts, the updateTag function includes a runtime check:
export function updateTag(tag: string) {
const workStore = workAsyncStorage.getStore()
// Check if we're NOT in a Server Action (also catches route handlers)
if (!workStore || workStore.page.endsWith('/route')) {
throw new Error(
'updateTag can only be called from within a Server Action. ' +
'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead.'
)
}
// ... rest of implementation
}
The function checks:
- If there's a
workStore(Server Action context) - If the current page ends with
/route(route handler), it throws
###Why This Design?
updateTag is specifically designed for read-your-own-writes scenarios where:
- A user makes a change (e.g., creates a post)
- The UI immediately shows the fresh data
- The cache is invalidated right away
This behavior only makes sense in Server Actions (which are called directly from forms/buttons) where you control both the mutation and the immediate redirect.
###What to Use Instead
In a route handler, use revalidateTag instead:
// ❌ This will throw an error
export async function POST() {
updateTag('posts') // Error!
}
// ✅ Use revalidateTag with a profile
export async function POST() {
revalidateTag('posts', 'max') // Works in route handlers
}
The key differences:
updateTag: Server Actions only, immediate expiration, blocks until fresh data is fetchedrevalidateTag: Works everywhere, can use profiles like'max'for stale-while-revalidate behavior
END OF POST