Structured logging for serverless Next.js
6 min read

Structured logging for serverless Next.js

console.log stops being enough once real users show up. How I send structured logs from Next.js route handlers and serverless functions, and why I flush before every function returns.

For a long time, logging in my apps meant console.log. It works until something goes wrong in production. Then I'm scrolling through the host's function logs looking for a line that says "failed", with no user, no order id and no idea which request it belonged to.

This post is the setup I use now: structured log entries from server code, sent to Pullwish with @pullwish/logger, and the one habit that matters most on serverless: sending the logs before the function returns.

Why console.log stops being enough

Plain console.log has three problems once an app has real users:

  1. No structure. A log line is a string. Searching for every failed payment for one user means grepping text and hoping you wrote the message the same way each time.
  2. No levels you can act on. Debug noise and real errors end up in the same stream.
  3. It lives next to the deploy, not the product. The errors, the feedback and the logs for the same feature end up in three different places.

What I want instead is a log entry with a level, a short stable message, a category, the user it happened to, and the details as JSON.

One logger module for the server

@pullwish/logger is a small SDK that batches log entries and sends them to your Pullwish project. It works in Node.js, in the browser and in edge runtimes. I keep one instance in a module and import it everywhere:

// lib/logger.ts
import { createLogger } from "@pullwish/logger";

export const logger = createLogger({
  apiKey: process.env.PULLWISH_API_KEY!,
  projectId: process.env.PULLWISH_PROJECT_ID!,
  source: "server",
  minLevel: process.env.NODE_ENV === "production" ? "info" : "debug",
});

The API key needs the logs:write permission. Each Pullwish API key is created with its own permission scopes under Settings → API Keys, so I give the logger a key of its own with just logs:write. The CLI doesn't set this one up for you, unlike the other SDKs.

source is a tag added to every entry. I use "server" for route handlers and "worker" for background jobs, so I can tell them apart later.

Log events, not sentences

The habit that made logs useful for me: keep the message short and stable, and put everything that changes into data.

logger.info("Payment processed", {
  category: "billing",
  userId: "u_456",
  data: { amount: 1900, plan: "indie" },
});

logger.warn("Slow query", {
  category: "db",
  data: { queryMs: 850, table: "users" },
});

"Payment processed" is the same string every time, so it's easy to search for. The amount, the plan and the query time sit in data as JSON instead of being glued into the message. category groups related entries, and userId ties an entry to the user it happened to.

There are five levels: trace, debug, info, warn and error. Anything below minLevel is dropped in the SDK before it's sent, so debug logging can stay in the code without filling up production. If the level is decided at runtime, logger.log(level, message, opts) takes it as an argument.

The serverless catch: flush before you return

The logger doesn't send every entry right away. It queues them and sends a batch when 10 entries are waiting or after 5 seconds, whichever comes first (both are configurable with batchSize and flushInterval). That keeps the number of requests down.

On a long-running Node.js server that's all you need, because the SDK also flushes on beforeExit and SIGTERM. Serverless and edge functions are different. The function can be finished before the 5-second timer fires, and edge runtimes have no process exit to hook into at all. So I call await logger.flush() before the handler returns:

// app/api/checkout/route.ts
import { logger } from "@/lib/logger";

export async function POST(req: Request) {
  const { userId, amount } = await req.json();

  try {
    await processPayment(userId, amount);
    logger.info("Payment processed", { category: "billing", userId, data: { amount } });
    return Response.json({ ok: true });
  } catch (err) {
    logger.error("Payment failed", {
      category: "billing",
      userId,
      data: { error: (err as Error).message, amount },
    });
    return Response.json({ error: "Payment failed" }, { status: 500 });
  } finally {
    await logger.flush();
  }
}

Putting the flush in finally means it runs on both paths. flush() never throws, so a logging problem can't turn a successful request into a failed one.

What I don't put in logs

Structured logs make it tempting to dump whole objects into data. I don't. No API keys, tokens, passwords, connection strings or full card details, and no request bodies passed through unfiltered. I log ids and the few fields I'd actually need to debug: an order id, a status code, a duration. If I wouldn't paste it into a bug report, it doesn't go in a log.

Reading the logs

Entries show up in the Pullwish dashboard under Event Logs. You can filter by level and search the messages, and each row shows the category, the source and the time. Opening an entry shows its data, the user and the rest of the details.

The part I like most is that errors from @pullwish/error-tracker appear in the same view as error-level entries. So when I'm looking at a failed checkout, the exception and the log lines around it are in one list, in the same project as the feature requests and bug reports for that part of the app.

Through Pullwish's MCP, the same logs are available in Cursor too. list_event_logs returns recent entries for a project and can filter by level, so I can ask for the latest errors without leaving the editor.

Limits worth knowing

A few numbers from the API reference, so nothing surprises you:

  • Up to 100 entries per request (the SDK sends 10 by default), and a request body of up to 512 KB.
  • A message can be up to 5,000 characters.
  • 300 requests per 5 minutes per API key.

Event logging is included on Indie, Startup and Business. The free Hobby plan doesn't include it, and the API answers 403 there. New accounts get Indie free for 14 days, with no card required.

The short version

One logger module, a key with only logs:write, short stable messages with the details in data, and await logger.flush() before a serverless function returns. That's the whole setup, and it's the difference between "something failed" and knowing which user, which request and why.

The full option list and more examples are in the @pullwish/logger docs at docs.pullwish.com.

AI Disclaimer: This article was drafted with AI assistance. I reviewed, edited and fact-checked it against the product before publishing.