I thought my server actions were fast until I added logging, then analytics, then revalidation... and then suddenly it's like "hold on, let me finish these three different errands before I actually send a response."
But this makes no sense, right? The user already has what they need, so why are we making them wait?
Let me show you exactly what happens when you add logging, analytics, and revalidation to your server actions, and how the after
function can save the day.
See the difference: waiting for everything vs. getting response immediately while background tasks run
Traditional approach - user waits for everything
User gets response immediately, background tasks continue
after
FunctionWhat if instead we gave the user the response instantly (because that's what they truly care about) and moved all this extra work to the background? That's exactly what the after
function in Next.js lets you do.
It's like telling your app: "Send the user what they need right now and deal with all these chores later in the background."
That's exactly what we do in the "fast" demo with the after
function.
after
Function?The after
function allows you to schedule work to be executed after a response is finished. This is useful for tasks and other side effects that don't need to block the response, such as:
after
?The after
function can be used in:
generateMetadata
where you generate SEO tags)So mainly on the server side.
Anytime you see there's a lot of work being executed in your server action or server-side code, divide it into:
Then move the work that can happen in the background for stuff that the user doesn't have to wait for into the after
function.
The after
function is all about keeping things blazing fast without blocking the user. You use it in places where you have important work that the user needs immediately, and non-important work that can happen in the background.
✅ DO Use | ❌ DON'T Use |
---|---|
Work that's important for the user's immediate needs | The user needs the result of the background work |
Work that's not critical and can happen later | The background work is critical for the operation to succeed |
Operations that might be slow (emails, webhooks, analytics) | You need to handle errors from the background work immediately |
Tasks that don't require immediate feedback | The background work must complete before the response is valid |
The after
function is a powerful tool in Next.js that helps you:
By strategically using after
, you can build applications that feel instant to users while still handling all the necessary background tasks that modern applications require.