Skip to Content

API reference

Reference for linkpeek's preview() and parseHTML(): presets, every option, the typed result fields, HTTP error handling and the error codes.

The root export provides preview, parseHTML, presets, URL validation helpers, and typed errors in ESM and CommonJS.

Fetch a URL

preview(url, options?) returns Promise<PreviewResult>.

Fetch an HTTP(S) URL, validate redirects, enforce timeout and byte limits, then extract preview metadata. Invalid input, policy failures, timeouts and network failures throw LinkpeekError; a caller abort rethrows the signal's reason.

HTML responses with an HTTP error status still resolve with extracted metadata. Check result.statusCode before caching or displaying a successful card. Direct image, video and audio responses populate the corresponding media URL field.

import { preview } from "linkpeek";

const result = await preview("https://example.com/article");
if (result.statusCode < 400) {
  console.log(result.title ?? result.siteName);
}

Options

OptionTypeDefaultDescription
timeoutnumber8000Deadline in milliseconds for the whole call (redirects, body read and any meta-refresh hop), from 0 to 2,147,483,647. Throws LinkpeekError code TIMEOUT when elapsed; invalid values throw INVALID_OPTIONS
maxBytesnumber30_000Maximum decoded response-body bytes to retain. result.truncated reports when the limit cut the head (or the document, with includeBodyContent)
userAgentstring"Twitterbot/1.0"User-Agent sent with requests
followRedirectsbooleantrueFollow HTTP redirects after validating each target
maxRedirectsnumber10Maximum redirects per call, HTTP and meta refresh combined. Must be a non-negative integer; invalid values throw INVALID_OPTIONS
headersRecord<string, string>{}Extra non-sensitive request headers. Common credential-bearing headers are rejected; custom headers are not forwarded on cross-origin redirects
allowPrivateIPsbooleanfalseAllow private/internal IP targets
resolveHost(hostname) => Promise<string[]>noneOpt-in DNS check on the first request and every redirect hop; private answers throw PRIVATE_NETWORK_BLOCKED, lookup errors and empty answers throw FETCH_FAILED (a LinkpeekError, resolver error in cause). Example in DNS checks
signalAbortSignalnoneCancel the request from the caller side
fetchtypeof fetchglobalThis.fetchCustom fetch implementation. It must honor manual redirects and the supplied abort signal; a response.url it reports is validated too
followMetaRefreshbooleanfalseFollow one <head> <meta http-equiv="refresh"> redirect with a delay of 10s or less
includeBodyContentbooleanfalseContinue scanning <body> for JSON-LD and image fallbacks

Result fields

All result fields are present. Optional metadata uses null when unavailable; titles and images are not guaranteed.

Extracted resource URLs are resolved against the document base and limited to HTTP(S). Text fields are trimmed with whitespace runs collapsed; blank values count as missing. JSON-LD fields all come from one entity: the first article, product or similar content entity, else a page entity, never a site-wide Organization or WebSite. For every field the first usable tag wins.

FieldTypeDescription
urlstringFinal fetched URL; parseHTML() returns the canonical URL
statusCodenumberHTTP status code. parseHTML() returns 0
titlestring | nullog:title -> twitter:title -> Dublin Core -> <title> -> JSON-LD headline or name of the page's main entity
descriptionstring | nullog:description -> twitter:description -> meta[name=description] -> JSON-LD -> Dublin Core
imagestring | nullPreview image URL
imageAltstring | nullImage alt text
imageWidthnumber | nullog:image:width
imageHeightnumber | nullog:image:height
siteNamestringog:site_name -> JSON-LD publisher -> JSON-LD WebSite name -> hostname
faviconstring | nullDeclared favicon, or the origin’s /favicon.ico as a fallback guess
mediaTypestringog:type, defaults to "website"
canonicalUrlstringCanonical URL, og:url, or fetched URL
authorstring | nullJSON-LD author, author meta, or Dublin Core creator
localestring | nullog:locale
langstring | nullHTML language, content-language, or locale prefix
publishedDatestring | nullArticle, JSON-LD, or Dublin Core date
keywordsstring[] | nullmeta[name=keywords]
videostring | nullSafe og:video URL
videoTypestring | nullog:video:type MIME type, or the content type of a direct video URL; null without a video
audiostring | nullSafe og:audio URL
twitterCardstring | nullTwitter card type
twitterSitestring | nullTwitter site handle
twitterCreatorstring | nullTwitter creator handle
twitterPlayerstring | nulltwitter:player embed URL (an iframe page), http(s) only
twitterPlayerStreamstring | nulltwitter:player:stream raw media URL, http(s) only
themeColorstring | nullTheme color
oEmbedUrlstring | nullDiscovered oEmbed endpoint URL. Not fetched
truncatedbooleanmaxBytes cut the response before the end of <head> (or of the document with includeBodyContent); raise maxBytes to read later tags. parseHTML() returns false

Parse existing HTML

parseHTML(html, baseUrl, options?) returns PreviewResult synchronously, with statusCode: 0. It makes no network requests. baseUrl must be an absolute HTTP(S) URL; anything else throws LinkpeekError code INVALID_URL rather than inventing a site name, favicon and canonical URL. Both url and canonicalUrl contain the resolved canonical URL. The options object accepts includeBodyContent; fetch options such as maxBytes do not limit a supplied HTML string.

Use the parser directly when HTML is already available. Default parsing stops tokenizing at the end of the head. Set includeBodyContent: true only when body JSON-LD or image fallback is worth the extra work.

Typed errors

import { LinkpeekError, preview } from "linkpeek";

try {
	await preview(url);
} catch (error) {
	if (error instanceof LinkpeekError) {
		console.log(error.code); // "TIMEOUT", "PRIVATE_NETWORK_BLOCKED", …
	}
}

Use code, never message matching, for program flow. A caller abort rethrows the signal's reason as-is; every other failure is a LinkpeekError.

CodeMeaning
INVALID_URLURL could not be parsed or contains credentials
UNSUPPORTED_PROTOCOLURL does not use HTTP(S)
PRIVATE_NETWORK_BLOCKEDTarget matches a blocked hostname or literal address
SENSITIVE_HEADERCustom headers include a prohibited credential-bearing name
INVALID_OPTIONSAn option fails validation
TOO_MANY_REDIRECTSThe redirect limit was reached
TIMEOUTThe call exceeded its timeout
FETCH_FAILEDThe network request, body read or resolveHost lookup failed; the original error is cause

Presets

presets.fast is the default: maxBytes: 30_000, includeBodyContent: false, followMetaRefresh: false. presets.quality uses maxBytes: 200_000 and enables both flags. Spread a preset to override individual options.

import { preview, presets } from "linkpeek";

await preview(url, { ...presets.quality, timeout: 5_000 });

URL validation helpers

validateUrl(url, allowPrivateIPs?) returns void on success or throws LinkpeekError. isPrivateHost(hostname) returns a boolean for hostnames and literal IPs covered by the blocklist. It normalises the host the way fetch() does, so shorthand IPv4 such as 127.1, 2130706433 or 0x7f000001 is caught, and it blocks internal names (localhost, *.internal, *.local, *.localdomain, *.intranet, *.private, *.corp, *.home, *.lan, *.home.arpa, single-label names such as metadata). Neither helper performs DNS resolution.

import { isPrivateHost, validateUrl } from "linkpeek";

isPrivateHost("127.0.0.1"); // true
isPrivateHost("2130706433"); // true (127.0.0.1)
isPrivateHost("metadata.google.internal"); // true
validateUrl("http://169.254.169.254/"); // throws PRIVATE_NETWORK_BLOCKED

TypeScript and CommonJS

The root export includes PreviewOptions, PreviewResult and LinkpeekErrorCode types. Requires Node.js 22.12+; ESM and CommonJS each have their own declarations.

import type { PreviewOptions, PreviewResult } from "linkpeek";

// CommonJS:
const { preview } = require("linkpeek");