API Reference
Complete reference for all openlink functions and options.
preview
The main function to fetch and parse link preview metadata from a URL.
import { preview } from "openlink"
const data = await preview("https://github.com")Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | The URL to fetch and parse |
options | PreviewOptions | Optional configuration |
Options
| Option | Type | Default | Description |
|---|---|---|---|
timeout | number | 10000 | Request timeout in milliseconds |
headers | Record<string, string> | See below | Custom headers to send |
followRedirects | boolean | true | Whether to follow redirects |
fetch | typeof fetch | globalThis.fetch | Custom fetch function |
includeRaw | boolean | false | Include raw parsed metadata |
includeOembed | boolean | false | Include oEmbed data if available |
includeJsonLd | boolean | false | Include JSON-LD structured data |
validateUrl | boolean | true | Validate URL before fetching |
retry | number | 0 | Number of retry attempts on failure |
retryDelay | number | 1000 | Initial delay between retries in ms |
Default headers:
{
"User-Agent": "OpenLinkBot/1.0 (+https://openlink.sh)",
"Accept": "text/html,application/xhtml+xml"
}Examples
Basic usage:
const data = await preview("https://github.com")
console.log(data.title)With options:
const data = await preview("https://github.com", {
timeout: 5000,
includeRaw: true,
headers: {
"Accept-Language": "en-US"
}
})Custom fetch for testing:
const data = await preview("https://example.com", {
fetch: mockFetch
})parse
Parse an HTML string for Open Graph, Twitter Card, and standard meta tags. Use this when you already have the HTML content.
import { parse } from "openlink"
const html = await fetch("https://example.com").then(r => r.text())
const metadata = parse(html)Parameters
| Parameter | Type | Description |
|---|---|---|
html | string | The HTML string to parse |
Returns
Returns a ParseResult object with all extracted metadata fields.
Example
import { parse } from "openlink"
const html = `
<html>
<head>
<title>My Page</title>
<meta property="og:title" content="My Open Graph Title">
<meta property="og:image" content="https://example.com/image.png">
</head>
</html>
`
const result = parse(html)
console.log(result.ogTitle) // "My Open Graph Title"
console.log(result.title) // "My Page"extract
Extract and normalize metadata from a parsed result. Combines Open Graph, Twitter Card, and HTML meta tags with proper fallbacks.
import { parse, extract } from "openlink"
const parsed = parse(html)
const result = extract(parsed, "https://example.com")Parameters
| Parameter | Type | Description |
|---|---|---|
parsed | ParseResult | Output from parse() |
url | string | Original URL for resolving relative paths |
Returns
Returns a normalized PreviewResult object.
Example
import { parse, extract } from "openlink"
const html = await fetch(url).then(r => r.text())
const parsed = parse(html)
const result = extract(parsed, url)
console.log(result.title) // Normalized title
console.log(result.image) // Absolute image URLisValidUrl
Check if a string is a valid URL.
import { isValidUrl } from "openlink"
isValidUrl("https://github.com") // true
isValidUrl("not-a-url") // false
isValidUrl("github.com") // false (no protocol)Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | The string to validate |
Returns
Returns boolean.
normalizeUrl
Normalize a URL by adding protocol if missing and resolving relative paths.
import { normalizeUrl } from "openlink"
normalizeUrl("github.com") // "https://github.com"
normalizeUrl("/path", "https://example.com") // "https://example.com/path"
normalizeUrl("example.com/page") // "https://example.com/page"Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | The URL to normalize |
base | string | Optional base URL for relative paths |
Returns
Returns the normalized URL string.
withRetry
Wrap any async function with retry logic and exponential backoff.
import { withRetry, isRetryable } from "openlink"
const result = await withRetry(
() => fetch("https://example.com"),
{ retries: 3, delay: 1000, backoff: 2 }
)Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (attempt: number) => Promise<T> | Function to retry |
options | RetryOptions | Retry configuration |
Options
| Option | Type | Default | Description |
|---|---|---|---|
retries | number | 3 | Max retry attempts |
delay | number | 1000 | Initial delay in ms |
backoff | number | 2 | Backoff multiplier |
shouldRetry | (error, attempt) => boolean | () => true | Whether to retry |
isRetryable
Check if an error should be retried.
import { isRetryable, PreviewError } from "openlink"
const error = new PreviewError("timeout", "TIMEOUT")
isRetryable(error) // true
const invalid = new PreviewError("invalid", "INVALID_URL")
isRetryable(invalid) // falseRetryable error codes: TIMEOUT, FETCH_ERROR, HTTP_ERROR (429 or 5xx).
createProxyFetch
Create a fetch function that routes requests through a proxy.
import { createProxyFetch, preview } from "openlink"
const proxiedFetch = createProxyFetch(
"https://proxy.example.com/?url={url}"
)
const data = await preview("https://github.com", {
fetch: proxiedFetch
})Parameters
| Parameter | Type | Description |
|---|---|---|
proxyUrl | string | Proxy URL template with {url} placeholder |
baseFetch | typeof fetch | Base fetch function |
corsProxy / allOriginsProxy
Helper functions for common CORS proxy services.
import { corsProxy, allOriginsProxy } from "openlink"
corsProxy("https://example.com")
// "https://corsproxy.io/?https%3A%2F%2Fexample.com"
allOriginsProxy("https://example.com")
// "https://api.allorigins.win/raw?url=https%3A%2F%2Fexample.com"createCache
Create a cache wrapper for preview results.
import { createCache, memoryCache, preview } from "openlink"
const storage = memoryCache()
const cache = createCache(storage)
await cache.set("https://example.com", result, 3600000)
const cached = await cache.get("https://example.com")Parameters
| Parameter | Type | Description |
|---|---|---|
storage | CacheStorage | Storage backend with get/set/delete |
withCache
Wrap preview function with automatic caching.
import { createCache, memoryCache, withCache, preview } from "openlink"
const cache = createCache(memoryCache())
const cachedPreview = withCache(cache, preview)
const data = await cachedPreview("https://github.com", {
cacheTtl: 3600000
})memoryCache
Simple in-memory cache storage for development and testing.
import { memoryCache, createCache } from "openlink"
const storage = memoryCache()
const cache = createCache(storage)
storage.clear()getImageSize
Detect image dimensions without downloading the full image.
import { getImageSize } from "openlink"
const size = await getImageSize("https://example.com/image.png")
console.log(size) // { width: 1200, height: 630, type: "png" }Parameters
| Parameter | Type | Description |
|---|---|---|
url | string | Image URL |
options.fetch | typeof fetch | Custom fetch function |
options.timeout | number | Timeout in ms (default: 5000) |
Returns
Returns { width, height, type } or null if detection fails.
Supported formats: PNG, JPEG, GIF, WebP.