Deno nuggets: Get user agent

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to get user agent in Deno?

// From chromeMozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36// From SafariMozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15

Solution

The user agent is always present in the standard HTTP header: User-Agent. The user agent header is implementation specific, but usually contains detailed information about the browser, operating system, versions, etc.

The user agent can be read from the user-agent header present in the Request body.

Here is the code:

import { serve } from "https://deno.land/std/http/mod.ts";function reqHandler(req: Request): Response {
console.log("User agent is", req.headers.get("user-agent"));
return new Response(null);
}
serve(reqHandler);

Here are some tests:

// From curlUser agent is curl/7.79.1// From FirefoxUser agent is Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0// From chromeMozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36// From SafariMozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15

To know about own user agent (useful in fetch calls), the navigator.userAgent attribute can be used:

navigator.userAgent;Deno/1.22.0

--

--