Dependency-free robots.txt parser and allow/disallow matcher for Node.js, following RFC 9309 — Robots Exclusion Protocol.
Parsing and matching are pure functions over strings: no network, no I/O. Fetch the file however you like and pass its text in.
npm install @mk-techi/robotsRequires Node.js 20 or later. ESM only.
import { parseRobotsTxt, isAllowed, crawlDelay } from "@mk-techi/robots";
const robots = parseRobotsTxt(`
User-agent: *
Disallow: /admin
Allow: /admin/public
Disallow: /*.pdf$
User-agent: Googlebot
Allow: /
Crawl-delay: 2
Sitemap: https://example.com/sitemap.xml
`);
isAllowed(robots, "https://example.com/admin/users"); // false
isAllowed(robots, "https://example.com/admin/public/help"); // true (longest rule wins)
isAllowed(robots, "/report.pdf"); // false
isAllowed(robots, "/admin", "Googlebot/2.1"); // true (named group beats *)
crawlDelay(robots, "Googlebot"); // 2
robots.sitemaps; // ["https://example.com/sitemap.xml"]Parses robots.txt content into user-agent groups and sitemap URLs. Never throws.
- Consecutive
User-agentlines share one group; a new group starts only once the current group has rules. Allow,DisallowandCrawl-delayare kept as rules, in file order. Rules that appear before anyUser-agentline are dropped.Sitemaplines are collected globally, wherever they appear.- Comments (
#), unknown directives and malformed lines are ignored.
url may be an absolute URL or a path; the path and query string are matched.
/robots.txtitself is always allowed, with or without a query string (RFC 9309 §2.2.2).- Group selection, matching the agent's product token case-insensitively
(
Googlebot/2.1→googlebot):- If one or more groups name the agent, only those groups apply and the
*group is ignored. - If several groups name the agent, their rules are combined into one set before matching, as RFC 9309 §2.2.1 requires.
- Otherwise every
*group applies, combined the same way. With no applicable group, everything is allowed.
- If one or more groups name the agent, only those groups apply and the
- The longest matching
Allow/Disallowpattern wins;Allowwins ties. *matches any sequence of characters, a trailing$anchors to the end of the path.- An empty
Disallow:matches nothing. A URL matching no rule is allowed.
Returns the Crawl-delay in seconds for the applicable group, or null if it declares
none or the value is not a non-negative number. Crawl-delay is not part of RFC 9309
but is widely used.
interface RobotsRule { directive: "allow" | "disallow" | "crawl-delay"; path: string }
interface RobotsGroup { userAgents: string[]; rules: RobotsRule[] }
interface RobotsTxt { groups: RobotsGroup[]; sitemaps: string[] }MIT