When someone books, there's work they need to see finished, deducting the spots, and work they don't: sending them an email, writing down what happened in a log. The mail client from the previous lesson can spend twenty seconds retrying. If the action waits for it, the person stares at a disabled button because of something they don't care about; if it's fired off without waiting, the process can stop halfway through without anyone noticing.

after offers the middle ground: it schedules a function for when the response has gone out, and asks the platform to keep it alive until it finishes. It's convenient, and it has very specific limits, because it isn't a job queue. In this lesson you'll use it for the email and the audit log, you'll set up a scheduled task for orphaned files and you'll learn to recognize when something more robust is needed.

  1. Waiting, firing or deferring

Compare three ways of sending the email from bookSpots:

// 1. Waiting: correct and slow
await confirmBooking(bookingId)

// 2. Firing without waiting: fast and with no guarantee
void confirmBooking(bookingId)

// 3. Deferring
import { after } from 'next/server'
after(() => confirmBooking(bookingId))

The second one seems to work on your machine, where the process never stops. On a serverless platform, execution can be frozen as soon as the response is sent, and the promise is left half-done until another request comes in, or forever. On your own server, a restart cuts it off without warning. And if it rejects, nobody handles it.

With after, Next.js knows there's pending work:

sequenceDiagram
    participant N as Browser
    participant S as Server
    participant C as Mail API
    N->>S: bookSpots
    S->>S: transaction and cache notifications
    S->>S: after(task): just records it
    S-->>N: response with the refreshed event page
    Note over S: the response has finished
    S->>C: send the email, with retries
    C-->>S: accepted
  • The function runs when the response has finished, including one streamed in chunks.
  • It runs even if the response doesn't end well: if an error is thrown, or if redirect or notFound is called. But after must have been called beforehand: whatever comes after a redirect never runs.
  • after doesn't return anything to wait for. Its result can't affect the response, which has already gone out.
  • It can be nested and wrapped in your own functions.

  1. Where from

Place after? cookies() and headers() inside the function
Server Action Yes Yes
Route Handler Yes Yes
Server Component, generateMetadata Yes No: read them first and pass the value
proxy.ts Yes The data is available in the request itself
Client Component No

There's a reason for the difference in the third row. Next.js needs to know which part of the tree reads request data to decide what goes into the shell, and after runs when rendering has already finished. Calling cookies() there throws an error. Read it in the component and capture the value.

2.1. In a Server Component, carefully

after isn't a request API: it doesn't make the route dynamic. In a prerendered page, the function runs at build time and on every revalidation, not on every visit. This visit counter wouldn't count a single one:

// Wrong: the event page is in the shell
async function EventContent({ params }: Pick<Props, 'params'>) {
  const { slug } = await params
  after(() => countVisit(slug))
  // …
}

For it to happen on every visit, the component has to stay out of the prerender, in a hole of its own:

// Example only
import { io } from 'next/cache'
import { headers } from 'next/headers'
import { after } from 'next/server'

async function VisitLogger({ slug }: { slug: string }) {
  await io() // From here on, only within a request
  const agent = (await headers()).get('user-agent') ?? 'unknown' // Before after

  after(() => logVisit(slug, agent))
  return null
}

// In the page
<Suspense fallback={null}>
  <VisitLogger slug={slug} />
</Suspense>

You've known this since 05-04: rendering is reading, and a read mustn't have consequences that matter. An approximate visit log is acceptable; deducting something isn't. For analytics, a client component is usually better, and it doesn't count bots or prefetches either.

  1. A wrapper for errors

Nobody waits for the result, so a failure only exists if we write it down. Every task will go through here:

// lib/tasks/after-response.ts
import 'server-only'
import { after } from 'next/server'

export function afterResponse(name: string, task: () => Promise<unknown>): void {
  after(async () => {
    try {
      await task()
    } catch (error) {
      console.error(`Task "${name}" failed:`, error)
    }
  })
}

The name makes it searchable in the logs. In 10-05 this catch will send the error to the observability system, and there will be a single place to change.

  1. The confirmation email

The task needs to know which booking to confirm. createBooking must return its identifier:

// lib/data/bookings.ts
export type BookingResult =
  | { status: 'booked'; bookingId: string; spotsBefore: number; spotsAfter: number }
  // … the rest doesn't change

// In createBooking, step 4
const [booking] = await tx
  .insert(bookings)
  .values({ userId, eventId, spots })
  .returning({ id: bookings.id })

// … and in the return value
return {
  status: 'booked',
  bookingId: booking.id,
  spotsBefore: event.spotsLeft,
  spotsAfter: event.spotsLeft - spots,
}

// Addition
export async function getBookingForNotification(bookingId: string) {
  const db = await getDb()
  const [row] = await db
    .select({
      spots: bookings.spots,
      name: users.name,
      email: users.email,
      title: events.title,
      slug: events.slug,
      startsAt: events.startsAt,
      venue: venues.name,
    })
    .from(bookings)
    .innerJoin(users, eq(bookings.userId, users.id))
    .innerJoin(events, eq(bookings.eventId, events.id))
    .innerJoin(venues, eq(events.venueId, venues.id))
    .where(eq(bookings.id, bookingId))
    .limit(1)
  return row ?? null
}
// lib/tasks/confirm-booking.ts
import 'server-only'
import { sendEmail } from '@/lib/mail'
import { getBookingForNotification } from '@/lib/data/bookings'
import { formatDateTime, formatSpots } from '@/lib/format'
import { SITE_NAME, SITE_URL } from '@/lib/site'

export async function confirmBooking(bookingId: string): Promise<void> {
  const booking = await getBookingForNotification(bookingId)
  if (!booking) return // Canceled in the meantime

  const link = new URL(`/events/${booking.slug}`, SITE_URL).href
  await sendEmail({
    to: booking.email,
    subject: `Your booking: ${booking.title}`,
    text: [
      `Hi ${booking.name},`,
      `You've booked ${formatSpots(booking.spots)} for "${booking.title}".`,
      `${formatDateTime(booking.startsAt)}, at ${booking.venue}.`,
      link,
      SITE_NAME,
    ].join('\n\n'),
    key: `booking-confirmed:${bookingId}`,
  })
}
// actions/bookings.ts, in bookSpots, after checking that the status is 'booked'
const { bookingId } = booking
notifyIfAvailabilityChanges(booking.spotsBefore, booking.spotsAfter)
afterResponse('confirm booking', () => confirmBooking(bookingId))
  • The identifier is captured, not the data. The task reads whatever is there at the moment of sending; if the booking was canceled in the meantime, it sends nothing.
  • The email is outside the transaction, as we asked for in 06-01: no row is left locked by a third-party server.
  • The idempotency key comes from the booking. If this task ever runs twice, the person will get one message.
  • Cache notifications are sent earlier, in the action. They must be part of the response.
  • The success message doesn't promise the email. "You've booked 2 spots" is true; "We've sent you an email" is something we don't know yet. At most, "We'll send you one".
FAILURES=2 node scripts/mail-api.mjs   # In another terminal

Book a spot: the event page updates right away and, a couple of seconds later, the simulator shows two 503s and a 202 with the message. Now stop it and book another event: the interface doesn't notice anything, and the failure stays in the Next.js terminal. That email has been lost. Keep that picture in mind for section 8.

  1. The audit log

It's useful to know who did what. A separate table that only ever grows:

// lib/db/schema.ts (addition)
export const auditLog = pgTable(
  'audit_log',
  {
    id: text('id').primaryKey().default(generatedId),
    userId: text('user_id'),
    action: text('action').notNull(),
    entityId: text('entity_id').notNull(),
    requestId: text('request_id'),
    occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull(),
  },
  (table) => [index('audit_log_entity_idx').on(table.entityId, table.occurredAt)],
)
// lib/data/audit.ts
import 'server-only'
import { getDb } from '@/lib/db/client'
import { auditLog } from '@/lib/db/schema'

export type AuditedAction =
  | 'booking.created'
  | 'booking.canceled'
  | 'event.saved'
  | 'event.submitted'

export interface AuditEntry {
  userId: string
  action: AuditedAction
  entityId: string
  requestId: string | null
  occurredAt: Date
}

export async function addAuditEntry(entry: AuditEntry): Promise<void> {
  const db = await getDb()
  await db.insert(auditLog).values(entry)
}
// lib/tasks/audit.ts — only from Server Actions and Route Handlers
import 'server-only'
import { headers } from 'next/headers'
import { type AuditedAction, addAuditEntry } from '@/lib/data/audit'
import { REQUEST_ID_HEADER } from '@/lib/proxy/request-id'
import { afterResponse } from '@/lib/tasks/after-response'

export function audit(userId: string, action: AuditedAction, entityId: string): void {
  const occurredAt = new Date() // Now, not when it's written

  afterResponse(`audit ${action}`, async () => {
    const requestId = (await headers()).get(REQUEST_ID_HEADER) // Allowed in here
    await addAuditEntry({ userId, action, entityId, requestId, occurredAt })
  })
}
// actions/bookings.ts
audit(user.id, 'booking.created', bookingId) // In bookSpots
audit(user.id, 'booking.canceled', bookingId) // In cancelMyBooking, if it was canceled

Generate and apply the migration (npm run db:generate -- --name audit-log and npm run db:migrate). In editEvent the entry is recorded the same way, with event.saved or event.submitted depending on the intent. The place is the function it passes to saveEvent, once updateEvent has returned true: that way it happens before the redirect, and only if something was written.

The request identifier the proxy set in 07-02 links this row to the log lines. The user_id column is deliberately not a foreign key: if a user is deleted, the history remains.

That said, should it go in after? It depends on what it's for:

Purpose Where it's written
An aid for investigating; losing the odd row is tolerable after
An obligation: if it can't be recorded, the operation mustn't happen Inside the operation's transaction

Ours is of the first kind. An audit required by regulations is of the second, and it will also have retention periods and restricted access: check with whoever handles compliance. And in any case, store identifiers and don't copy personal data.

  1. The limits

after works with next start and in Docker with no configuration. On serverless platforms it depends on whether they offer a primitive equivalent to waitUntil, and in a static export it doesn't exist.

  • The duration is the route's. The work has to fit within the limit the platform sets for the function. maxDuration declares it; for Server Actions it's set on the page that uses them:
// app/(public)/events/[slug]/page.tsx (addition)
export const maxDuration = 30 // Seconds. The mail retries' deadline is 20
  • next start doesn't enforce it: it's a hint for platforms. On your own server, the limit is the process staying alive.
  • Shutdown. On SIGTERM, Next.js finishes in-flight requests and pending after functions before exiting. The infrastructure has to wait: the documentation recommends between 10 and 30 seconds (11-05). A power cut, a SIGKILL or an out-of-memory failure don't wait for anyone.
  • There are no retries. If it fails, it failed; the only retries are the ones you write inside.
  • There's no persistence. Pending work lives only in the process's memory.
  • It competes for the same resources. Each task uses pool connections and CPU from the server handling visits. A hundred bookings per second means a hundred simultaneous sends.
  • Nobody's watching. Without logs or alerts, failures are invisible.

One question settles it: what happens if this doesn't run? If the answer is "not much", after. If it's "someone doesn't get something we owe them", you need another tool.

  1. Scheduled tasks

The orphaned files from 06-05 don't depend on any request: they need to be collected every night. Next.js doesn't include a scheduler, and a setInterval in instrumentation.ts would be multiplied by the number of instances and wouldn't exist on serverless platforms. The usual approach is for something external (the system's cron, the platform's scheduler, CI) to call a protected endpoint.

The script used the disk directly. So that the task works with any storage, we extend the interface:

// lib/storage/types.ts
export interface StoredFile {
  key: string
  modifiedAt: Date
}

// In the FileStorage interface
list(): Promise<StoredFile[]>

// lib/storage/disk.ts, in diskStorage (imports readdir and stat)
async list() {
  const dir = path.join(readEnv().filesDir, 'events')
  await mkdir(dir, { recursive: true })

  const files: StoredFile[] = []
  for (const name of await readdir(dir)) {
    const key = `events/${name}`
    if (!isImageKey(key)) continue
    files.push({ key, modifiedAt: (await stat(pathFor(key))).mtime })
  }
  return files
},
// lib/tasks/clean-files.ts
import 'server-only'
import { isNotNull } from 'drizzle-orm'
import { getStorage } from '@/lib/storage'
import { getDb } from '@/lib/db/client'
import { events } from '@/lib/db/schema'

const ONE_DAY = 24 * 60 * 60 * 1000

export async function cleanFiles(
  now: Date,
): Promise<{ deleted: number; failed: number }> {
  const storage = getStorage()
  const files = await storage.list() // Before the database (06-05)

  const db = await getDb()
  const rows = await db
    .select({ image: events.image })
    .from(events)
    .where(isNotNull(events.image))
  const used = new Set(rows.map(({ image }) => image))

  let deleted = 0
  let failed = 0
  for (const { key, modifiedAt } of files) {
    if (used.has(key) || now.getTime() - modifiedAt.getTime() < ONE_DAY) continue
    try {
      await storage.remove(key)
      deleted++
    } catch (error) {
      failed++
      console.error(`Could not delete ${key}:`, error)
    }
  }
  return { deleted, failed }
}
// app/api/tasks/clean-files/route.ts
import { guarded, errorResponse } from '@/lib/api/responses'
import { readEnv } from '@/lib/env'
import { hasBearerKey } from '@/lib/security/bearer-key'
import { cleanFiles } from '@/lib/tasks/clean-files'

export const maxDuration = 60

export async function POST(request: Request) {
  return guarded(async () => {
    if (!hasBearerKey(request, readEnv().tasksKey)) {
      return errorResponse('unauthorized', 'Invalid key.')
    }

    const result = await cleanFiles(new Date())
    console.info('File cleanup', result)
    return Response.json(result, { status: result.failed > 0 ? 500 : 200 })
  })
}
# lib/env.ts: TASKS_KEY: optional → tasksKey
# .env.local: TASKS_KEY=dev-only-key
curl -fsS -X POST -H 'Authorization: Bearer dev-only-key' \
  localhost:3000/api/tasks/clean-files

# A server's crontab: every night at 4:10
# 10 4 * * * curl -fsS -m 90 -X POST -H "Authorization: Bearer $TASKS_KEY" https://agendaviva.example/api/tasks/clean-files

Delete scripts/clean-files.ts and the files:clean entry from package.json: the task replaces them.

  • after isn't used here, on purpose. The caller is a scheduler that can wait, and what makes it useful is knowing whether it went well. With curl -f, a 500 becomes a visible failure. Answering 202 and working afterwards would hide the result; it's only worth it if the scheduler cuts off very early.
  • It's repeatable and can overlap. Deleting something already deleted doesn't fail, and two simultaneous runs do the same thing.
  • One failure doesn't stop the rest.
  • Each task gets its own key, or a shared one that's different from all the others. Never a provider's.
  • Some schedulers can only make GET requests. It's accepted with the same check, knowing it's an exception; the authorization header keeps it from being prerendered, because it reads the request.

  1. When you need a queue

Let's go back to the lost email. If the confirmation were an essential ticket, trying wouldn't be enough: you'd have to store the intent with the same guarantee as the booking. That's the outbox pattern: in the same transaction that writes the booking, a "this still needs sending" row is inserted. If the transaction commits, the intent exists; if it's rolled back, so is the intent.

flowchart LR
    A["bookSpots"] --> T["Transaction:<br/>booking + pending row"]
    T --> R["Response"]
    P["Scheduler<br/>every minute"] --> W["Task: takes a batch"]
    W --> C["Mail API"]
    C -- "accepted" --> H["Marks it as sent"]
    C -- "fails" --> E["Adds an attempt<br/>and postpones the next one"]
    E -. "too many attempts" .-> M["Manual review"]
// Sketch: not part of the project
// In createBooking, inside the transaction
await tx.insert(outbox).values({ type: 'confirm-booking', reference: booking.id })

// In the task the scheduler calls every minute
const batch = await db.transaction(async (tx) => {
  const rows = await tx
    .select()
    .from(outbox)
    .where(and(isNull(outbox.doneAt), lte(outbox.nextAttempt, new Date())))
    .orderBy(asc(outbox.nextAttempt))
    .limit(20)
    .for('update', { skipLocked: true }) // Another run takes different rows

  // Claim the batch for a while: if the process dies, the rows become available again
  if (rows.length > 0) {
    await tx
      .update(outbox)
      .set({ nextAttempt: inFiveMinutes, attempts: sql`${outbox.attempts} + 1` })
      .where(inArray(outbox.id, rows.map(({ id }) => id)))
  }
  return rows
})
// Then, outside the transaction: send the batch and mark the accepted ones

The send isn't in the transaction, so it can happen and never get marked. When it's repeated, the idempotency key prevents the duplicate: you need both pieces. It's the mirror image of the webhook: there, others repeated themselves to us; here, we repeat ourselves.

And they combine well: after to try right away, and the outbox to pick up whatever was left behind. As volume grows, queue libraries on top of PostgreSQL or managed services add priorities, dashboards and workers in separate processes.

In the request after Scheduled task Outbox or queue
The caller waits Yes No There's nobody No
Survives a restart It fails and you know No Next time Yes
Retries Your own, short Your own, short On the next run For hours
When it happens Now Right after On schedule Right after or later
Complexity None Minimal A scheduler Table, task and monitoring
In AgendaViva Deducting spots Email, audit Orphans Not needed today

Common Mistakes and Tips

  • A promise that isn't awaited instead of after.
  • Calling after after redirect.
  • Leaving to after something the response takes for granted.
  • cookies() or headers() inside after in a Server Component.
  • Expecting it to run on every visit to a prerendered page.
  • Not catching errors, or not logging them.
  • Treating it like a queue: thousands of sends, jobs that take minutes, obligations.
  • Retries longer than maxDuration or than the shutdown time.
  • A setInterval on the server as a scheduler.
  • A task endpoint without a key, or one that accepts everyone if the variable is missing.
  • Answering 202 to a scheduler and never finding out about failures.
  • A task that can't be repeated.

Exercises

Exercise 1: choosing the tool

Choose between doing it in the request, after, a scheduled task or an outbox: (a) deducting spots; (b) measuring how long a search took; (c) notifying 300 people that an event has been canceled; (d) deleting external notifications older than 90 days; (e) generating a PDF the person will download right now; (f) deleting the previous poster after replacing it.

Solution

  • (a) In the request: it's what's being asked for.
  • (b) after. Losing the odd measurement doesn't matter.
  • (c) Outbox. It's a lot of sends, with a rate limit, and failing to notify someone is serious.
  • (d) Scheduled task.
  • (e) In the request, if it's quick. If it takes a while, the job is stored, a worker does it and the browser polls a status endpoint (04-06).
  • (f) after would be reasonable, because the nightly cleanup collects whatever fails. Waiting for it, as in 06-05, is fine too: with the disk it's instant.

Exercise 2: fixing an action

Find the problems and rewrite it with the pieces from this lesson.

export async function submitForReview(eventId: string) {
  const user = await getPlaceholderOrganizer()
  after(async () => {
    await markInReview(user.id, eventId)
    refresh()
  })
  notifyAdmins(eventId)
  redirect('/dashboard/events')
  after(() => logSubmission(eventId))
}

Solution

  1. The status change is inside after: the list it redirects to would show the previous status, and the change might never happen.
  2. refresh makes no sense once the response has gone out.
  3. notifyAdmins is fired without waiting.
  4. The second after comes after redirect.
  5. It doesn't validate the argument.
export async function submitForReview(eventId: string) {
  if (!identifier.safeParse(eventId).success) throw new Error('Invalid event')
  const user = await getPlaceholderOrganizer()

  const changed = await markInReview(user.id, eventId)
  if (changed) {
    afterResponse('notify review', () => notifyAdmins(eventId))
    audit(user.id, 'event.submitted', eventId)
  }
  refresh()
  redirect('/dashboard/events')
}

Exercise 3: reminders

Design the task that, every morning, sends an email reminder for the next day's bookings. It must be able to run twice without duplicating messages, respect the provider's limit and not stop if one send fails. Write the function and explain what you'd do if the guide grew to tens of thousands of bookings a day.

Solution

// lib/tasks/remind-bookings.ts — practice only
const BATCH_SIZE = 5

export async function remindBookings(now: Date): Promise<{ sent: number; failed: number }> {
  const bookings = await listBookingsByDay(formatIsoDay(addOneDay(now)))
  let sent = 0

  for (let i = 0; i < bookings.length; i += BATCH_SIZE) {
    const results = await Promise.all(
      bookings.slice(i, i + BATCH_SIZE).map((booking) =>
        sendEmail({
          to: booking.email,
          subject: `Tomorrow: ${booking.title}`,
          text: `${formatDateTime(booking.startsAt)}, at ${booking.venue}.`,
          key: `reminder:${booking.id}`,
        }),
      ),
    )
    sent += results.filter(({ status }) => status === 'accepted').length
  }
  return { sent, failed: bookings.length - sent }
}

sendEmail doesn't throw, so Promise.all is safe, and the key makes the second run harmless as long as the provider remembers it. The day is computed in the guide's time zone (04-01), not in UTC. listBookingsByDay and addOneDay are left for you to write.

With tens of thousands, it wouldn't fit within a request's duration: the task would insert rows into the outbox and another, frequent one would send them in batches. That way, an interruption halfway through doesn't force you to start over.

Conclusion

after schedules work for when the response has finished, from actions, Route Handlers, Server Components and the proxy, with access to the request in the first two. It doesn't hold anyone up, and the end of the request doesn't take it down with it, but it doesn't retry, doesn't persist and has to fit within the route's duration. For periodic work there's a protected endpoint and an external scheduler; for what must be guaranteed, a row written in the same transaction and something that processes it. AgendaViva now confirms bookings by email, records who did what and cleans up its files every night.

That's the end of module 7. The application serves people and programs, intercepts requests, verifies signatures and works when nobody is waiting. And it still has the same gap we pointed out in 06-01: every booking belongs to usr-01, the dashboard is open and the audit log always records the same person. We've learned to recognize machines; what's missing is recognizing people. Module 8, Authentication and Security, starts with Sessions and Secure Cookies.

© Copyright 2026. All rights reserved