Hey, it's finally happened. I've decided to write a blog post. And if you're reading this, I've also finished one. I have wanted to do this for a long time, but could never find the motivation to start. But you know what they say: anger is the best motivator. They do say that, right?Some context that's in the backgroundWe're going on a journey, you and I. But first, we need to set the scene. Imagine we're working for $COMPANY and one of our Next.js services did an oopsie. This being Next.js, we of course have no idea what actually happened since the default logging is only enabled during development.Our quest is to go in and setup some production ready logging. It's not going to be easy, but then again, nothing ever is.Middleware? Middle of nowhere!The first step of our journey is the middleware. The documentation even states this:Middleware executes before routes are rendered. It's particularly useful for implementing custom server-side logic like authentication, logging, or handling redirects.Alright, looks simple enough. Time to pick a logging library. I went with pino since we have used it before. Anything is an upgrade over console.log anyways. We'll get this done before lunch.Let's set up a basic middleware:// middleware.ts import { NextResponse, NextRequest } from "next/server"; export async function middleware(request: NextRequest) { return new NextResponse.next({ request: request, headers: request.headers, // status: 200, // statusText: 'OK' }); } export const config = { matcher: "/:path*", };I think we already have a problem here. You can pass a grand total of 4 parameters from your middleware. The only thing that actually affects the invoked route is the headers. Let's not skip over the fact that you can't have multiple middlewares or chain them either. How do you fuck this up so bad? We've had middlewares since at least the early 2010s when Express came out.Anyways, we're smart and modern Node.js has some pretty nifty tools. Let's reach for AsyncLocalSto...
First seen: 2025-09-02 08:50
Last seen: 2025-09-02 16:52