Middleware only log first request
Unanswered
Cuban Crocodile posted this in #help-forum
Cuban CrocodileOP
I am using Middleware with App Router, and am attempting to write some basic access logs for my application. I've mostly achieved that, but there's a problem. The middleware is firing correctly on every request, but I am looking to make it only log the first request. So for instance, if I visit "http://localhost:3000" I just want that to be logged, not the subsequent requests such as "http://localhost:3000/_next/static/css/app/layout.css?v=1720813361107" etc. I am not sure if this is possible, but I wanted to see if anyone knew.
Here is my current code
Here is my current code
import { NextRequest, NextResponse } from "next/server";
// Use this to get better location once I have a working version: https://ip-api.com/docs/api:json
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
const ip = request.headers.get("CF-Connecting-IP");
const country = request.headers.get("CF-IPCountry");
const url = JSON.stringify(request.url);
const userAgent = JSON.stringify(request.headers.get("user-agent"));
const statusCode = NextResponse.next().status;
const method = request.method;
console.log(
`${method} ${statusCode} ${url} User Agent:${userAgent} IP:${ip} Country:${country}`
);
}2 Replies
Sun bear
Did you check the matcher part of the documentation?
https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
You can define paths like that
https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
You can define paths like that
Cuban CrocodileOP
I did see it, but that's essentially just regex, right? I'm not sure how I could achieve what I'm looking for with that.