< PHP MASTER />

Next Js Background Task by using the after function

Learn how to run background tasks in Next.js using the after() function. we will see how it works, why it improves performance, and see real-world practicle examples.

Sajid Ali14-02-20263 min read

Modern applications need to be fast. But real apps don’t just return a response — they also perform background operations like sending emails, updating analytics, logging user activity, or updating order tracking.

Traditionally these operations made APIs slow because the server waited for them before responding. The Next.js after() functionsolves this problem by allowing you to run code after the response is sent.

What is after() in Next.js?

after() is a server-side function introduced in Next.js 14.2+ that executes code after the HTTP response has already been delivered to the user.

That means the user does not wait for heavy operations like sending emails. The page loads instantly while background tasks continue on the server.

Problem Before after()

Normally when you write an API route, every operation blocks the response.

js
export async function POST(req) {

  const order = await createOrder();

  await sendEmail(order);       // slow
  await updateAnalytics(order); // slow
  await writeLogs(order);       // slow

  return Response.json({ success: true });
}

Here the user waits for email, analytics, and logging before getting a response. This leads to slow checkout experience and poor UX.

Using after() Function

js
import { after } from "next/server";

export async function POST(req) {

  const order = await createOrder();

  after(async () => {
    await sendEmail(order);
    await updateAnalytics(order);
    await writeLogs(order);
  });

  return Response.json({ success: true });
}

Now the response returns instantly and the background work continues on the server. This dramatically improves performance.

Next.js after() Function — Run Background Tasks Without Slowing Your API

In this video, you will learn how to use the Next.js after() function to execute background tasks after sending a response. We will build a real example including sending order emails, updating logs, and improving API performance. Perfect for eCommerce, authentication systems, and analytics tracking in modern Next.js applications.

Watch Video

Real World Example (Order Confirmation)

A typical e-commerce order should immediately show “Order placed successfully” while emails and tracking happen in the background.

js
import { after } from "next/server";

export async function POST(req) {

  const body = await req.json();
  const orderId = await DB.table("orders").insert(body);

  after(async () => {
    await EmailService.sendOrderDetails(body.email, orderId);
    await EmailService.sendOrderDetails(process.env.ADMIN_EMAIL, orderId);
  });

  return Response.json({
    success: true,
    orderId
  });
}

Users now get instant feedback, while the system still completes all required tasks.

Common Use Cases

  • Send welcome email
  • Order confirmation email
  • Analytics tracking
  • Activity logging
  • Webhook notifications
  • Cache revalidation
js
after(async () => {
  await revalidatePath("/blog");
});

Important Rules

  • after() works only on the server
  • It cannot be used inside client components
  • Do not return Response inside after()
  • Always handle errors using try/catch
js
after(async () => {
  try {
    await sendEmail();
  } catch (err) {
    console.error(err);
  }
});

Conclusion

The Next.js after() function allows you to run background jobs without queues or cron workers. It improves user experience by returning a response instantly while still performing heavy operations.

You should use after() for emails, analytics, logs, and post-processing tasks. It is one of the most important performance features introduced in modern Next.js.

Frequently Asked Questions

The after() function in Next.js allows developers to run code after the HTTP response has been sent to the user. It is mainly used for background tasks like sending emails, logging activity, updating analytics, or cache revalidation without slowing down the page response.
The after() function runs only on the server side. It works inside Route Handlers, Server Actions, and Server Components in the App Router. It cannot be used inside client components or useEffect.
Common use cases include sending order confirmation emails, logging user activity, triggering webhooks, updating analytics, writing audit logs, and revalidating cached pages. It helps improve performance by preventing users from waiting for these tasks.
Yes. Since the response is returned immediately and heavy operations run afterward, the API response time becomes much faster. This improves user experience, reduces waiting time, and positively affects Core Web Vitals and SEO.
after() is suitable for lightweight background tasks, but it cannot fully replace job queues. For heavy or long-running processing such as video encoding or large data processing, dedicated queues or workers are still recommended.
The after() function is available starting from Next.js 14.2 and is fully supported in Next.js 15 and later versions using the App Router.
Tags:
Next.jsNext.js after()Background JobsServer ActionsPerformance OptimizationReact Server Components
Sajid Ali

Author

Sajid Ali

Software Developer

Software developer passionate about writing clean, scalable, and maintainable code. Focused on building elegant user interfaces and great developer experiences.