# metafetch

> Metafetch fetches a given URL's title, description, images, links etc.

Latest version **7.0.1** (published 2026-11-04) · MIT license · 0 weekly downloads

## Install

```sh
npm install metafetch
pnpm add metafetch
yarn add metafetch
bun add metafetch
```

Provides the command `metafetch`.

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 7.0.1 |
| Published | 2026-11-04 |
| First published | 2014-12-09 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=22.12.0 |
| Dependencies | 1 |
| Unpacked size | 34.1 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 21 |
| Author | brahma-dev |
| Maintainers | brahma-dev |
| Keywords | meta, html-head, twitter-cards, structured-data, head-tags, canonical-urls, page-title, meta-description, meta-tags, semantic-web, social-media-metadata, web scraping, open-graph, json-ld, scraping |

## Links

- npm: https://www.npmjs.com/package/metafetch
- Repository: https://github.com/brahma-dev/metafetch
- Issues: https://github.com/brahma-dev/metafetch/issues
- npm.io page: https://npm.io/package/metafetch

## Dependencies (1)

- [linkedom](https://npm.io/package/linkedom.md) >=0.13.7

## Alternatives

- [base64url](https://npm.io/package/base64url.md) — 6.1M weekly downloads
- [get-installed-path](https://npm.io/package/get-installed-path.md) — 502.9K weekly downloads
- [@uppy/url](https://npm.io/package/@uppy/url.md) — 185.8K weekly downloads
- [@d3fc/d3fc-shape](https://npm.io/package/@d3fc/d3fc-shape.md) — 16.2K weekly downloads
- [localizer](https://npm.io/package/localizer.md) — 226 weekly downloads

## Recent versions

- 7.0.1 (latest) — 2026-11-04
- 7.0.0 — 2026-11-04
- 6.0.0 — 2026-04-22
- 5.0.4 — 2026-02-28
- 5.0.3 — 2025-11-19
- 5.0.2 — 2025-10-30
- 5.0.1 — 2025-08-13
- 5.0.0 — 2025-08-13
- 4.1.0 — 2025-08-13
- 4.0.1 — 2025-08-12
- 4.0.0 — 2025-08-12
- 3.2.0 — 2024-08-10
- 3.1.8 — 2024-08-08
- 3.1.7 — 2024-08-08
- 3.1.6 — 2024-04-03
- … 57 more at https://npm.io/package/metafetch/versions

## README

# Node metafetch

[![Build Status](https://github.com/brahma-dev/metafetch/actions/workflows/build.yml/badge.svg)](https://github.com/brahma-dev/metafetch/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/brahma-dev/metafetch/branch/main/graph/badge.svg)](https://codecov.io/gh/brahma-dev/metafetch)
[![coveralls](https://coveralls.io/repos/github/brahma-dev/metafetch/badge.svg?branch=main)](https://coveralls.io/github/brahma-dev/metafetch?branch=main)
[![Known Vulnerabilities](https://snyk.io/test/npm/metafetch/badge.svg?style=flat)](https://snyk.io/test/npm/metafetch)
[![NPM version](https://img.shields.io/npm/v/metafetch.svg?style=flat)](https://www.npmjs.org/package/metafetch)

**Metafetch** is a library to fetch and parse metadata from a web page. It can extract standard meta tags, Open Graph data, JSON-LD, favicons, and feeds, and even render client-side JavaScript to get data from Single-Page Applications (SPAs).

## Table of Contents

-   [Key Features](#key-features)
-   [Installation](#installation)
-   [CLI Usage](#cli-usage)
-   [API Usage](#api-usage)
    -   [Basic Example](#basic-example)
    -   [Advanced Example (Rendering SPAs & Retries)](#advanced-example-rendering-spas--retries)
    -   [Performance Optimization Example](#performance-optimization-example)
-   [API](#api)
    -   [`metafetch.fetch(url, [options])`](#metafetchfetchurl-options)
    -   [Available Flags](#available-flags)
-   [Instance Management](#instance-management)
-   [Response Data](#response-data)
-   [AI Agent Skills](SKILL.md)
-   [License](#license)

## Key Features

*   **Comprehensive Metadata:** Extracts title, description, URL, site name, images, links, and more.
*   **Client-Side Rendering:** Uses **Puppeteer** to render JavaScript-heavy sites, ensuring you get the metadata even from SPAs (e.g., React, Vue, Svelte).
*   **Robust Network Handling:** Features built-in **request retries with exponential backoff** to handle transient network errors gracefully.
*   **Rich Content Discovery:**
    *   Finds the best-quality **favicon** by prioritizing Apple touch icons and largest sizes.
    *   Discovers **RSS/Atom feeds** linked in the page.
    *   Extracts **Video and Audio** sources from meta tags and media elements.
    *   Supports **oEmbed** discovery for embedding content.
    *   Extracts **Microdata and RDFa** as nested objects.
    *   Fetches and parses the **Web App Manifest**.
    *   Parses and flattens structured **JSON-LD** data.
*   **Advanced Encoding Detection:** Accurately detects character encoding via BOM, HTTP headers, and meta tags to prevent garbled text.
*   **Highly Configurable:** Fine-tune requests with custom headers, user agents, and feature flags to parse only what you need.
*   **Performance Optimizations:**
    *   **Early Exit (Head-Only):** Option to stop downloading the page as soon as the `</head>` tag is reached, saving bandwidth and time.
    *   **Selective JSON-LD:** Pre-screen and parse only the specific JSON-LD types you care about to reduce CPU and memory usage.

## Installation

Use NPM to install:

```bash
npm install metafetch
```

*Note: **`puppeteer`** is a peer dependency and must be installed separately (`npm install puppeteer`) if you want to use the SPA / client-side rendering feature.*

## CLI Usage

Metafetch comes with a built-in CLI for quick metadata extraction.

```bash
# Using Node.js (npx)
npx metafetch https://example.com

# Using Bun (bunx)
bunx metafetch https://example.com

# With performance optimizations
npx metafetch https://example.com --head-only --pretty
```
# Filtering specific JSON-LD types
npx metafetch https://example.com --jsonld-types Product,Recipe

# Using rendering for SPAs
npx metafetch https://example.com --render
```

### CLI Options

| Option | Description |
|---|---|
| `--format, -f <fmt>` | Output format: `json`, `summary`, `kv` (default: `summary` for TTY, `json` otherwise). |
| `--render` | Enable Puppeteer rendering (requires `puppeteer` to be installed). |
| `--head-only` | Stop downloading after `</head>` (faster, non-render only). |
| `--jsonld-types <t>` | Comma-separated list of JSON-LD types to filter. |
| `--user-agent <ua>` | Custom User-Agent string. |
| `--flags <f>` | Comma-separated list of flags (e.g., `links=false,images`). |
| `--pretty` | Pretty-print the JSON output. |
| `--version`, `-v` | Show version number. |
| `--help`, `-h` | Show help message. |

## API Usage

### Basic Example

Here's a simple example using `async/await`.

```javascript
import metafetch from 'metafetch';

async function getMeta(url) {
  try {
    const meta = await metafetch.fetch(url);
    console.log(meta);
  } catch (err) {
    console.error(err);
  }
}

getMeta('https://example.com');
```

This will output a representative object like this:

```js
{
  title: 'Awesome Web Page',
  description: 'A compelling description of the page content, often used by search engines.',
  type: 'article',
  url: 'https://example.com/article-path',
  originalURL: 'https://example.com',
  ampURL: 'https://example.com/article-path/amp',
  siteName: 'Example News',
  charset: 'utf-8',
  image: 'https://example.com/images/featured-image.png',
  favicon: 'https://example.com/favicons/apple-touch-icon.png',
  feeds: [ 'https://example.com/rss.xml' ],
  videos: [ 'https://example.com/video.mp4' ],
  audio: [ 'https://example.com/podcast.mp3' ],
  oEmbed: 'https://example.com/services/oembed?url=...',
  meta: {
     'og:title': 'Awesome Web Page',
     'og:description': 'A compelling description...',
     'ld:headline': 'Awesome Web Page',
     /* ... other meta and JSON-LD tags ... */
  },
  jsonLd: [ { "@context": "https://schema.org", "@type": "NewsArticle", ... } ],
  microdata: [ { "@type": "https://schema.org/Recipe", "name": "Mom's Pie", ... } ],
  rdfa: [ { "@type": "Movie", "name": "Inception", ... } ],
  manifest: { name: "My App", short_name: "App", ... },
  images: [ 'https://example.com/images/featured-image.png', /* ... */ ],
  links: [ 'https://example.com/another-page', /* ... */ ],
  headers: { 'content-type': 'text/html; charset=utf-8', /* ... */ },
  language: 'en'
}
```

### Advanced Example (Rendering SPAs & Retries)

To get metadata from a client-rendered page or to make your request more robust, use the advanced options.

```javascript
import metafetch from 'metafetch';

async function getSpaMeta(url) {
  try {
    const meta = await metafetch.fetch(url, {
      // Use puppeteer to render the page
      render: true,

      // Retry up to 2 times on failure
      retries: 2,
      retryDelay: 1000, // 1 second base delay

      // Disable parsing of things you don't need
      flags: {
        images: false,
        links: false
      },
      
      // Pass custom options to the underlying fetch call
      fetch: {
        headers: {
          'Accept-Language': 'en-US,en;q=0.9'
        }
      }
    });

    console.log('Title:', meta.title);
    console.log('Description:', meta.description);

  } catch (err) {
    console.error(err);
  }
}

getSpaMeta('https://my-single-page-app.com');
```

### Dynamic User-Agent Example

The default User-Agent is static. To avoid being blocked and to mimic a real, up-to-date browser, you can supply a fresh User-Agent for each request using a helper library like `user-agents`.

First, install the library:

```bash
npm install user-agents
```

Then, generate a new User-Agent and pass it in the `fetch` options:

```javascript
import metafetch from 'metafetch';
import UserAgent from 'user-agents';

async function getMetaWithFreshAgent(url) {
  try {
    // Generate a new, random, and up-to-date User-Agent string.
    const userAgent = new UserAgent();
    console.log('Using User-Agent:', userAgent.toString());

    const meta = await metafetch.fetch(url, {
      userAgent: userAgent.toString()
    });

    console.log(meta.title);
  } catch (err) {
    console.error(err);
  }
}

getMetaWithFreshAgent('https://example.com');
```

### Performance Optimization Example

If you only need basic metadata (title, description, etc.) or specific structured data, use `headOnly` and `jsonLdTypes` to make your requests significantly faster.

```javascript
import metafetch from 'metafetch';

async function getFastMeta(url) {
  try {
    const meta = await metafetch.fetch(url, {
      // Abort connection as soon as </head> is found
      headOnly: true,
      
      // Only parse Product structured data
      jsonLdTypes: ['Product'],
      
      // Disable everything else
      flags: {
        images: false,
        links: false,
        microdata: false,
        rdfa: false
      }
    });

    console.log('Title:', meta.title);
    console.log('Products:', meta.jsonLd);
  } catch (err) {
    console.error(err);
  }
}

getFastMeta('https://example.com/product/123');
```

## API

### `metafetch.fetch(url, [options])`

Fetches and parses metadata from the given `url`.

#### Options (`FetchOptions`)

| Option | Type | Default | Description |
|---|---|---|---|
| `render` | `boolean` | `false` | If `true`, uses Puppeteer to render the page's JavaScript before parsing. |
| `retries` | `number` | `0` | Number of times to retry the request on failure. |
| `retryDelay` | `number` | `1000` | Base delay in milliseconds for retries (uses exponential backoff). |
| `userAgent`| `string` | Firefox | The User-Agent string to use for the request. |
| `headOnly` | `boolean` | `false` | If `true`, aborts the connection as soon as `</head>` is reached. Saves bandwidth but misses content in the `<body>`. |
| `jsonLdTypes`| `string[]`| `[]` | An array of `@type` strings (e.g., `['Product']`). If provided, only matching JSON-LD blocks are parsed and extracted. |
| `flags` | `object` | `{...}` | An object to enable/disable parsing specific fields. All flags are `true` by default. See the list below for all available flags. |
| `fetch` | `object` | `{}` | `RequestInit` options passed directly to the `fetch` call (e.g., `{ headers: {...} }`). |

### Available Flags

You can pass any of these boolean flags in the `flags` object to optimize parsing. For example, `flags: { links: false, images: false }` will skip extracting links and images.

*   `title`
*   `description`
*   `type`
*   `url`
*   `siteName`
*   `charset`
*   `image`
*   `meta` (includes all meta tags and flattened JSON-LD)
*   `images`
*   `links`
*   `headers`
*   `language`
*   `favicon`
*   `feeds`
*   `videos`
*   `audio`
*   `oEmbed`
*   `jsonLd`
*   `microdata`
*   `rdfa`
*   `manifest`

### Instance Management

You can create multiple instances of `Metafetch`, each with its own default User-Agent.

```javascript
import { Metafetch } from 'metafetch';

// Create an instance with a custom default User-Agent
const myBot = new Metafetch("MyPersonalBot/1.0");
await myBot.fetch('https://example.com');

// You can also change it later
myBot.setUserAgent("MyPersonalBot/2.0");
console.log(myBot.userAgent); // "MyPersonalBot/2.0"
```

## Response Data

| Field | Type | Description |
|---|---|---|
| `title` | `string` | The page's `<title>` tag. |
| `description` | `string` | The `og:description` or `description` meta tag. |
| `type` | `string` | The `og:type` meta tag (e.g., "website", "article"). |
| `url` | `string` | The final URL after redirects. Prioritizes `canonical` or `og:url`. |
| `originalURL`| `string` | The URL that was originally passed to the fetch method. |
| `ampURL` | `string` | The URL from a `<link rel="amphtml">` tag, if present. |
| `siteName` | `string` | The `og:site_name` meta tag. |
| `charset` | `string` | The detected character encoding of the page. |
| `image` | `string` | The `og:image` or `twitter:image` meta tag. |
| `favicon` | `string` | The best-quality favicon URL found on the page. |
| `feeds` | `string[]`| An array of RSS/Atom feed URLs discovered on the page. |
| `videos` | `string[]`| An array of video source URLs discovered on the page. |
| `audio` | `string[]`| An array of audio source URLs discovered on the page. |
| `oEmbed` | `string` | The oEmbed JSON discovery URL, if present. |
| `meta` | `object` | A key-value object of all meta tags and flattened JSON-LD data. |
| `jsonLd` | `object[]` | An array of original, un-flattened JSON-LD objects found on the page. |
| `microdata` | `object[]` | An array of nested Microdata items found on the page. |
| `rdfa` | `object[]` | An array of nested RDFa entities found on the page. |
| `manifest` | `object` | The parsed JSON content of the Web App Manifest, if present. |
| `images` | `string[]`| An array of all absolute image URLs on the page. |
| `links` | `string[]`| An array of all absolute hyperlink (`<a>`) URLs on the page. |
| `headers` | `object` | An object containing the final response's HTTP headers. |
| `language` | `string` | The content language (ISO 639-1) from the `<html>` tag or headers. |


## License

(The MIT License)

Copyright (c) 2026 Brahma Dev;

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

---
_Source: https://npm.io/package/metafetch · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
