I'm trying to access a request's User-Agent header from a route handler I have on my next.js project. Here is an example:
import { userAgent } from "next/server";
export const dynamic = "force-static";
export async function GET(req: Request) {
console.log(userAgent(req))
return Response.json({ error: false, message: "Hello, world!" });
}
The console.log
function returns this:
{
ua: '',
browser: { name: undefined, version: undefined, major: undefined },
engine: { name: undefined, version: undefined },
os: { name: undefined, version: undefined },
device: { vendor: undefined, model: undefined, type: undefined },
cpu: { architecture: undefined },
isBot: false
}
The above code is using the userAgent function, which I know is designed for middleware, but for some reason middleware doesn't seem to have an effect on Route Handlers. I've also tried:
and all of the approaches return a null
/empty string value. I know the request doesn't send a null user-agent because if I send a request to the same hosted project on Vercel and open up the Logs, the request shows a valid User-Agent column.
The issue is because you specify: export const dynamic = "force-static";
You’re telling Next.js to generate the route at build time. Static routes are pre-rendered and do not have access to the req
object at runtime because they are generated without a request context.
Also, in route handlers (like your GET function), you receive a standard Request object, and userAgent may not work as expected.
Remove/comment out force-static
and your agent data should appear in req.headers.get("user-agent")