OpenLink

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

ParameterTypeDescription
urlstringThe URL to fetch and parse
optionsPreviewOptionsOptional configuration

Options

OptionTypeDefaultDescription
timeoutnumber10000Request timeout in milliseconds
headersRecord<string, string>See belowCustom headers to send
followRedirectsbooleantrueWhether to follow redirects
fetchtypeof fetchglobalThis.fetchCustom fetch function
includeRawbooleanfalseInclude raw parsed metadata
includeOembedbooleanfalseInclude oEmbed data if available
includeJsonLdbooleanfalseInclude JSON-LD structured data
validateUrlbooleantrueValidate URL before fetching
retrynumber0Number of retry attempts on failure
retryDelaynumber1000Initial 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

ParameterTypeDescription
htmlstringThe 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

ParameterTypeDescription
parsedParseResultOutput from parse()
urlstringOriginal 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 URL

isValidUrl

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

ParameterTypeDescription
urlstringThe 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

ParameterTypeDescription
urlstringThe URL to normalize
basestringOptional 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

ParameterTypeDescription
fn(attempt: number) => Promise<T>Function to retry
optionsRetryOptionsRetry configuration

Options

OptionTypeDefaultDescription
retriesnumber3Max retry attempts
delaynumber1000Initial delay in ms
backoffnumber2Backoff multiplier
shouldRetry(error, attempt) => boolean() => trueWhether 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) // false

Retryable 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

ParameterTypeDescription
proxyUrlstringProxy URL template with {url} placeholder
baseFetchtypeof fetchBase 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

ParameterTypeDescription
storageCacheStorageStorage 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

ParameterTypeDescription
urlstringImage URL
options.fetchtypeof fetchCustom fetch function
options.timeoutnumberTimeout in ms (default: 5000)

Returns

Returns { width, height, type } or null if detection fails.

Supported formats: PNG, JPEG, GIF, WebP.

On this page