Skip to content
otncPublic

About

RSS, Atom and JSON Feed for Hono — done right.

Topics

Resources

Contributing

Stars

30 stars

Watchers

1 watching

Forks

Latest commit

 

History

391 Commits

Folders and files

Repository files navigation


English | 日本語

npm npm GitHub Workflow Status GitHub GitHub commit activity GitHub last commit

RSS, Atom and JSON Feed for Hono — done right.

Serving a feed sounds simple, but the details bite: dates have to be in the exact format each spec wants, text has to be XML-escaped, conditional requests should return 304, and readers ask for different formats through the Accept header. hono-feed takes care of all of that. You describe your feed once; it returns a correct HTTP Response.

Note

No runtime dependencies and only Web Standard APIs, so it runs wherever Hono runs: Cloudflare Workers, Deno, Bun and Node.js. hono is a peer dependency, and both v4 and v5 are supported, including the v5 release candidates (^4 || ^5.0.0-0 || >=5). Hono v5 is ESM-only and needs Node.js 22.12 or later, where require() can still load it.

Why hono-feed?

Hono has no feed helper, so the usual options are to write the XML by hand, or to use a general feed library and build the HTTP handling around it. hono-feed replaces both.

vs. hand-rolling the XML

import { Hono } from 'hono'

const app = new Hono()

// Before — fine in a demo, fragile in production
app.get('/feed', (c) => {
  const items = posts
    .map(
      (p) => `<item>
      <title>${p.title}</title>
      <link>${p.url}</link>
      <pubDate>${p.date.toUTCString()}</pubDate>
      <description>${p.body}</description>
    </item>`,
    )
    .join('')

  const xml = `<?xml version="1.0"?>
<rss version="2.0"><channel>
  <title>Example Blog</title>
  ${items}
</channel></rss>`

  return c.body(xml, 200, { 'Content-Type': 'application/rss+xml' })
})

A title containing & or < makes the XML invalid, and toUTCString() doesn't quite produce the RFC 822 date RSS expects. There is also no Atom or JSON output, no ETag / 304, no HEAD handling and no caching headers.

import { Hono } from 'hono'
import { serveFeed } from 'hono-feed'

const app = new Hono()

// After — correct by construction, and shorter
app.get('/feed', (c) =>
  serveFeed(c, {
    options: { title: 'Example Blog', link: 'https://example.com/', author: { name: 'You' } },
    items: posts.map((p) => ({ title: p.title, link: p.url, published: p.date, content: p.body })),
  }),
)

vs. a feed library

Libraries like feed or rss handle escaping and date formats, but they return a string. You still write the HTTP handling yourself:

import { Hono } from 'hono'
import { Feed as FeedKit } from 'feed'

const app = new Hono()

// Before — the library builds the document; you build the response
app.get('/feed', (c) => {
  const feed = new FeedKit({
    title: 'Example Blog',
    id: 'https://example.com/',
    link: 'https://example.com/',
    copyright: '',
  })
  for (const p of posts) {
    feed.addItem({ title: p.title, link: p.url, date: p.date, content: p.body })
  }

  // Format choice, Content-Type, negotiation, ETag/304, HEAD and caching are all up to you:
  return c.body(feed.rss2(), 200, { 'Content-Type': 'application/rss+xml' })
})

With hono-feed, this is the same single serveFeed call as the previous example, and negotiation, 304 and caching come with it.

Portability is the other difference. Many feed libraries are written for Node.js and use its built-in modules (Buffer, stream, fs), directly or through their dependencies. On Cloudflare Workers, Vercel Edge, Deno or Bun, that can mean adding polyfills, enabling a nodejs_compat flag, or not running at all. hono-feed has no dependencies and uses only Web Standard APIs, so the same code runs unchanged on all of them.

Hand-rolled A feed library hono-feed
XML escaping & date formats your job handled handled
RSS + Atom + JSON one format, more routes usually all three all three, negotiated
HTTP layer (negotiation, ETag / 304, HEAD, caching) DIY DIY built in
Output a string a string a Response
Workers / Vercel / Deno / Bun / Node up to your code depends on its deps runs everywhere (Web Standard)

Install

npm install hono-feed # or: pnpm add hono-feed / bun add hono-feed

The examples below use ESM import. With CommonJS, require('hono-feed') and every subpath (hono-feed/renderer, hono-feed/discovery, …) export the same names.

Quick start

Build a feed, add your items, and hand it to serveFeed:

import { Hono } from 'hono'
import { Feed, serveFeed } from 'hono-feed'

const app = new Hono()

app.get('/feed', (c) => {
  const feed = new Feed({
    title: 'Example Blog',
    link: 'https://example.com/',
    description: 'Notes and writing',
    author: { name: 'You' }, // Atom requires an author on the feed or on every item
    updated: new Date(),
  })

  feed.addItem({
    title: 'Hello, world',
    link: 'https://example.com/hello',
    published: new Date('2026-06-29'),
    content: '<p>My first post.</p>',
  })

  // Looks at the Accept header and replies with RSS, Atom or JSON (RSS by default).
  return serveFeed(c, feed)
})

export default app

This one endpoint serves all three formats without extra routes. A feed reader gets RSS, and a client that asks for application/json gets JSON Feed.

To pass plain data instead of using the builder, give serveFeed an object:

return serveFeed(c, { options: { title: 'Example Blog', updated: new Date() }, items: [] })

Choosing the format

By default the format is negotiated. To pin an endpoint to one format, as with the classic /rss.xml, /atom.xml and /feed.json, set format:

import { Hono } from 'hono'
import { serveFeed } from 'hono-feed'

const app = new Hono()

// `buildFeed()` stands for your own function that returns a Feed (or `{ options, items }`).
app.get('/rss.xml', (c) => serveFeed(c, buildFeed(), { format: 'rss' }))
app.get('/atom.xml', (c) => serveFeed(c, buildFeed(), { format: 'atom' }))
app.get('/feed.json', (c) => serveFeed(c, buildFeed(), { format: 'json' }))

When format isn't set, serveFeed works through these in order until one matches:

  1. ?format=rss|atom|json in the query — only if you opt in with detectFromQuery: true (or just detectFormatFromQuery: true)
  2. A URL extension like .rss / .atom / .json / .xml — on by default
  3. The Accept header, honouring q-values
  4. defaultFormat (which is 'rss')

Negotiated responses carry Vary: Accept, so caches store each format separately. Pinned ones don't, since they never change with the header.

Choosing a version from the query

detectFromQuery: true also lets ?version= choose the version. The value is read as the version type of the chosen format: RssVersion for rss, AtomVersion for atom and JsonFeedVersion for json. A version set in code, such as rssVersion in serveFeed(...), always takes precedence over the query.

app.get('/feed', (c) => serveFeed(c, buildFeed(), { detectFromQuery: true }))
// GET /feed?format=rss&version=0.91

A value outside the accepted set (see Feed versions) answers 400 Bad Request. A valid value that the feed data can't satisfy, such as ?version=0.91 without language, answers 422 Unprocessable Entity instead of throwing, because the request caused the failure. The same failure with a version set in code still throws, because that is a bug in the route. Both error responses send Cache-Control: no-store whatever cacheControl says, because the same URL can succeed once the feed data changes.

detectFromQuery turns on both detectFormatFromQuery and detectVersionFromQuery. Set one of them instead to detect only the format or only the version:

// Only ?format= is honoured; ?version= (if present) is ignored.
app.get('/feed', (c) => serveFeed(c, buildFeed(), { detectFormatFromQuery: true }))

Both query parameter names can be changed, for example to keep URLs short:

app.get('/feed', (c) =>
  serveFeed(c, buildFeed(), {
    detectFromQuery: true,
    formatQueryParam: 'f',
    versionQueryParam: 'v',
  }),
)
// GET /feed?f=rss&v=0.91

Cache-Control

cacheControl accepts the header value as a string. Hand-written directives are easy to get subtly wrong, with a missing comma or a misspelled directive, so it also accepts a CacheControlDirectives object:

app.get('/feed', (c) =>
  serveFeed(c, buildFeed(), {
    cacheControl: { public: true, maxAge: 600, staleWhileRevalidate: 60 },
  }),
)
// Cache-Control: public, max-age=600, stale-while-revalidate=60
Field Directive
public / private public / private
noStore / noCache no-store / no-cache
maxAge / sMaxAge max-age=<n> / s-maxage=<n>
mustRevalidate / proxyRevalidate must-revalidate / proxy-revalidate
immutable immutable
staleWhileRevalidate / staleIfError stale-while-revalidate=<n> / stale-if-error=<n>

false omits the header.

Prefer the object when its fields cover what you need, since it can't misspell a directive or drop a comma. The string form remains fully supported; use it for directives and vendor extensions that CacheControlDirectives doesn't have.

Extra response headers

Two optional headers cover cases that would otherwise need a wrapper around serveFeed. Neither is sent by default:

  • robots sends X-Robots-Tag. robots: 'noindex' keeps the feed out of search results, while readers can still fetch it.
  • contentDisposition sends Content-Disposition. Pass { filename: 'feed.xml' } for inline; filename="feed.xml", add type: 'attachment' to make browsers download the feed instead of rendering it, or pass a raw string to send it as-is. A non-ASCII filename also gets an RFC 8187 filename*. Control characters in either value throw, so a value taken from user input can't split the header.
serveFeed(c, input, {
  robots: 'noindex',
  contentDisposition: { filename: 'feed.xml', type: 'attachment' },
})

For CORS, use hono/cors; it already covers a feed fetched from a browser.

Skipping work on a 304

By default, serveFeed computes the ETag from the serialized body, so it can answer 304 only after your code has built the whole feed. If input comes from a database, every poll that finds nothing new still runs the query, and feed readers poll often.

Two options avoid that, and they can be combined:

  • etagFrom returns a value that is cheap to get before serializing, such as a content revision or a max(updated_at) result. serveFeed compares it with If-None-Match before touching input, and answers 304 right away on a match.
  • A lazy input, a function (): FeedInput | Feed | Promise<...> in place of the value, is called only when a response body is needed, so it never runs when etagFrom already answered 304.
app.get('/feed', (c) =>
  serveFeed(
    c,
    () => db.getFeedInput(), // only called when a body is actually needed
    { etagFrom: () => db.getRevision() }, // cheap: no need to load the full feed
  ),
)

etagFrom may return a value or a Promise. Once etagFrom or a lazy input is used, serveFeed returns Response | Promise<Response>, and its overloads give TypeScript that type automatically. A plain call, as in the other examples, still returns Response.

Things to know:

  • Only If-None-Match can be checked this early, because there is no updated date yet for If-Modified-Since. RFC 9110 §13.1.3 has a request with If-None-Match ignore If-Modified-Since anyway, so the common revalidation case is covered. A request with only If-Modified-Since resolves input as usual.
  • On a miss, the etagFrom value becomes the response's ETag, and the etag option is ignored. It is used as-is or wrapped in W/"…" by the same rule as a custom etag function. A bare tag that contains " or a control character throws, since the wrapped tag would be malformed and never match.
  • strictAccept's 406 and an invalid ?version='s 400 are both resolved before etagFrom or input are ever touched.

Sharing options with middleware

Instead of repeating the same options on every route, set them once with feedMiddleware. Each call can still override them.

import { Hono } from 'hono'
import { feedMiddleware, type FeedMiddlewareEnv } from 'hono-feed'

const app = new Hono<FeedMiddlewareEnv>()

app.use('*', feedMiddleware({ cacheControl: 'public, max-age=600' }))

// c.var.serveFeed already has the options above.
app.get('/feed', (c) => c.var.serveFeed(buildFeed()))

Using c.render()

If you prefer Hono's renderer pattern, feedRenderer connects serveFeed to c.render, the way jsxRenderer does for HTML. Pass it as route middleware and return c.render(input):

import { Hono } from 'hono'
import { feedRenderer } from 'hono-feed/renderer'

const app = new Hono()

app.get('/feed', feedRenderer({ baseUrl: 'https://example.com' }), (c) =>
  c.render(buildFeed(), { format: 'atom' }),
)

Note

feedRenderer augments Hono's global ContextRenderer type, so importing hono-feed/renderer anywhere makes c.render() accept a feed across your whole project. jsxRenderer makes the same trade-off. Because it has its own entry point, the augmentation applies only if you import it. To keep the helper scoped to a route, use feedMiddleware instead.

Static site generation

Hono's toSSG can write feeds to files at build time. It picks the file extension from the response's Content-Type but doesn't know the feed MIME types, so without a mapping a JSON feed would be saved as feed.json.html. feedExtensionMap maps them to .xml (RSS and Atom) and .json. Merge it with Hono's defaultExtensionMap, because toSSG replaces its own map with the one you pass:

import { Hono } from 'hono'
import { defaultExtensionMap, toSSG } from 'hono/ssg'
import { feedExtensionMap, serveFeed } from 'hono-feed'

const app = new Hono()
app.get('/rss', (c) => serveFeed(c, buildFeed(), { format: 'rss' })) // -> rss.xml
app.get('/feed.json', (c) => serveFeed(c, buildFeed(), { format: 'json' })) // -> feed.json

await toSSG(app, fs, { extensionMap: { ...defaultExtensionMap, ...feedExtensionMap } })

What goes in a feed

new Feed(options) describes the channel, and feed.addItem(item) adds an entry. Only title is required in every format. The other fields are optional in the shared model, and each maps to the matching field of every format. Each format also checks the fields its own spec requires (see the table after the example).

import { Feed } from 'hono-feed'

const feed = new Feed({
  title: 'Example Blog', // required
  link: 'https://example.com/',
  description: 'Notes and writing',
  language: 'en',
  author: { name: 'Ada', email: 'ada@example.com' },
  updated: new Date(),
})

feed.addItem({
  title: 'Hello, world', // required
  link: 'https://example.com/hello',
  description: 'A short summary',
  content: '<p>The full HTML body.</p>',
  published: new Date('2026-06-29'),
  categories: [{ term: 'intro' }],
})

Rather than emit a document that violates its spec, serveFeed checks these requirements first and throws a TypeError when one is missing:

Format The feed needs Every item needs
RSS link (falls back to feedUrl, then the request URL) —
Atom an author (here, or on every item) · updated when there are no items · id must be an absolute IRI id or link (ids must be absolute IRIs) · updated or published · link or content
JSON Feed — id or link · content or description

Deprecated versions add a few more, such as language for RSS 0.91, with equally specific error messages.

Enclosure.length is optional in the shared model, but RSS's <enclosure> requires the attribute. When it's unset, RSS emits length="0", following the RSS Best Practices Profile ("If the length of an enclosure cannot be determined, a publisher SHOULD use a length of zero"). JSON Feed omits size_in_bytes instead, since it's optional there.

An item's comments URL becomes <comments> in RSS 2.0 and <link rel="replies"> (RFC 4685) in Atom 1.0; JSON Feed has no equivalent.

Tip

hono-feed escapes XML for you but doesn't encode HTML entities. To turn arbitrary text into safe HTML for content or description, use he (he.encode(text)) with @types/he for its TypeScript types.

Absolute URLs in content

baseUrl turns URL fields (link, enclosure.url, …) into absolute URLs, but not the HTML in content or description. A feed reader has no page to resolve <img src="/a.png"> or <a href="/post"> against, so images and links in HTML from a CMS stop working. Set absolutizeContent: true in the feed options to rewrite them:

new Feed({ title: 'Blog', link: 'https://example.com/', absolutizeContent: true })
// <img src="/a.png"> -> <img src="https://example.com/a.png">

It resolves relative src, href, poster and srcset values in start tags against baseUrl. serveFeed defaults baseUrl to the request origin, and with no base at all nothing is rewritten. Text, comments, CDATA and the contents of <script> and <style> are left alone, and so is any value that is already absolute, a fragment, or another scheme such as mailto: or data:. It applies to RSS, Atom and JSON Feed, and is off by default.

Options

All options for serveFeed(c, input, options?):

Option Type Default What it does
format FeedFormat – Pin the format and skip negotiation
defaultFormat FeedFormat 'rss' Used when negotiation finds no match
detectFromExtension boolean true Read the format from .rss / .atom / .json / .xml
detectFromQuery boolean false Turn on both detectFormatFromQuery and detectVersionFromQuery
detectFormatFromQuery boolean detectFromQuery Read the format from ?format=
detectVersionFromQuery boolean detectFromQuery Read the version from ?version=
formatQueryParam string 'format' Query param name used to detect the format
versionQueryParam string 'version' Query param name used to detect the version
strictAccept boolean false Answer 406 Not Acceptable when the Accept header explicitly rejects every format (q=0), instead of falling back to defaultFormat
cacheControl string | CacheControlDirectives | false 'public, max-age=3600' Cache-Control header (see Cache-Control; false to omit)
etag boolean | ((body: string) => string) true Send an ETag and answer 304 on a match: true for the built-in weak FNV-1a-64 hash, a function for your own tag (e.g. from a revision you already track), or false to omit
etagFrom () => string | Promise<string> – Answer If-None-Match from a value that is cheap to get, without resolving input or serializing (see Skipping work on a 304)
lastModified boolean true Send Last-Modified from feed.updated
baseUrl string request origin Base for turning relative URLs into absolute ones
pretty boolean false Indent the output for readability
rssVersion RssVersion '2.0' Which RSS version / structure to emit
atomVersion AtomVersion '1.0' Which Atom version to emit
jsonFeedVersion JsonFeedVersion '1.1' Which JSON Feed version to emit
xmlVersion XmlVersion '1.0' XML declaration version. '1.1' is rejected for Atom and RSS 0.90 (their specs require XML 1.0)
suppressDeprecationWarnings boolean false Mute warnings for deprecated versions

Feed versions

The defaults, RSS 2.0, Atom 1.0 and JSON Feed 1.1, are the current recommended versions, so most projects never change them. The options are typed unions, so your editor offers only valid values:

Option Accepted values Default
rssVersion '2.0', '1.1', '1.0', '0.94', '0.93', '0.92', '0.91', '0.90' '2.0'
atomVersion '1.0', '0.3' '1.0'
jsonFeedVersion '1.1', '1' '1.1'
xmlVersion '1.0', '1.1' '1.0'

If you need an older version, note that RSS comes in two families. 0.91 through 0.94 and 2.0 share the familiar <rss version="…"> shape. The RDF family is a different document: 0.90 is Netscape's original "RDF Site Summary", 1.0 adds the Dublin Core and content modules, and 1.1 uses a <Channel> root. RSS 1.0 and 1.1 are supported, not deprecated; use them when a consumer specifically wants RDF.

Warning

RSS 0.9x, Atom 0.3 and JSON Feed 1.0 are deprecated. They still produce valid output, but each logs a coded DeprecationWarning once (HONOFEED_DEP000N; see HONOFEED_DEP.md for the list), through process.emitWarning on Node.js or console.warn on edge runtimes. To silence it, set suppressDeprecationWarnings: true or the HONO_FEED_NO_DEPRECATION environment variable, or run Node.js with --no-deprecation.

Podcasts

In RSS 2.0, the podcast field on FeedOptions (feed level) and FeedItem (episode level) adds typed podcast metadata from the iTunes namespace, which Apple Podcasts, Spotify and most directories require, and the Podcasting 2.0 namespace. xmlns:itunes and xmlns:podcast are declared automatically, and only when the feed uses a field from that namespace:

const feed = new Feed({
  title: 'My Show',
  link: 'https://example.com/',
  podcast: {
    author: 'Ada',
    category: ['Technology'],
    explicit: false,
    image: 'https://example.com/cover.jpg',
    owner: { name: 'Ada', email: 'ada@example.com' },
    type: 'episodic',
    subtitle: 'A show about things',
    summary: 'A longer description of the show, shown in place of <description> by some apps.',
    // block/complete emit an element only when true (Apple documents the value "Yes"); false or unset emits nothing.
    block: false,
    complete: false,
    // newFeedUrl: 'https://example.com/new-feed.xml', // set only once the feed has moved
    // Podcasting 2.0:
    guid: '917393e3-1b1e-5cef-ace4-edaa54e1f810',
    locked: true,
    funding: [{ url: 'https://example.com/support', text: 'Support the show' }],
  },
})

feed.addItem({
  title: 'Episode 1',
  link: 'https://example.com/1',
  enclosure: { url: 'https://example.com/1.mp3', type: 'audio/mpeg' },
  podcast: {
    duration: 1800, // itunes:duration, in seconds
    episode: 1,
    season: 1,
    episodeType: 'full',
    title: 'Pilot', // itunes:title: the episode title without numbering
    block: false,
    // Podcasting 2.0:
    transcript: [{ url: 'https://example.com/1.vtt', type: 'text/vtt' }],
    chapters: { url: 'https://example.com/1-chapters.json' },
  },
})

item.podcast.duration is optional. When it's unset, itunes:duration falls back to the item's enclosure.duration (above), so you don't have to repeat the duration under podcast.

podcast is ignored outside RSS 2.0, since the other RSS versions, Atom and JSON Feed have nothing to map it to. A customNamespaces entry for xmlns:itunes or xmlns:podcast always takes precedence over the automatic declaration.

More Podcasting 2.0 tags

Beyond guid / locked / funding / transcript / chapters, these Podcasting 2.0 elements are modeled:

Element Feed (options.podcast) Episode (item.podcast)
podcast:person person: [{ name, role?, group?, img?, href? }] same
podcast:license license: { identifier, url? } same
podcast:location location: { name, geo?, osm? } same
podcast:images images: { srcset } same
podcast:socialInteract socialInteract: [{ protocol, uri?, accountId?, accountUrl?, priority? }] same
podcast:medium medium: 'podcast' | 'music' | 'video' | … —
podcast:trailer trailer: [{ title, url, pubDate, length?, type?, season? }] —
podcast:season — podcastSeason: { number, name? }
podcast:episode — podcastEpisode: { number, display? }
feed.addItem({
  title: 'Episode 12.5',
  link: 'https://example.com/12-5',
  podcast: {
    person: [{ name: 'Ann Host', role: 'host', img: '/ann.jpg' }],
    license: { identifier: 'CC-BY-4.0' },
    podcastSeason: { number: 2, name: 'Race to Mars' },
    podcastEpisode: { number: 12.5, display: 'Ch.12.5' },
  },
})

URLs (img, href, the license url, uri, accountUrl, the trailer url) are resolved against baseUrl. podcastSeason and podcastEpisode are separate from the iTunes season and episode because the Podcasting 2.0 versions can carry a name or display label and a fractional number. podcast:value (Value4Value) and podcast:liveItem are not modeled; use customXml if you need them.

Feed discovery

Browsers and feed readers also need to find the feed. hono-feed/discovery generates the <link rel="alternate"> tags they look for, and the equivalent HTTP Link header, from the same MIME type table serveFeed uses, so the two always agree.

For an HTML <head>:

import { feedLinksHtml } from 'hono-feed/discovery'

app.get('/', (c) =>
  c.html(`
    <head>
      ${feedLinksHtml({ title: 'My Blog', rss: '/feed.rss', atom: '/feed.atom' })}
    </head>
  `),
)
// <link rel="alternate" type="application/rss+xml" title="My Blog" href="/feed.rss">
// <link rel="alternate" type="application/atom+xml" title="My Blog" href="/feed.atom">

With hono/jsx, map feedLinks() to <link> elements instead of using raw():

import { feedLinks } from 'hono-feed/discovery'

const FeedLinks = () => (
  <>
    {feedLinks({ title: 'My Blog', rss: '/feed.rss', atom: '/feed.atom' }).map((l) => (
      <link rel={l.rel} type={l.type} href={l.href} title={l.title} />
    ))}
  </>
)

feedLinks(options) returns the same data as an array ({ rel, type, href, title? }[]) instead of a string, for JSX or any other template engine. Both functions accept baseUrl to make relative feed URLs absolute. Without it, each href stays as given, and the browser resolves a relative one against the current page, which is usually what you want.

For the HTTP header form (RFC 8288), the feedLinkHeader middleware appends one Link header per configured format, only to responses whose Content-Type is HTML, since a feed response doesn't need links to its other formats:

import { feedLinkHeader } from 'hono-feed/discovery'

app.use('*', feedLinkHeader({ rss: '/feed.rss' }))
// Link: </feed.rss>; rel="alternate"; type="application/rss+xml"

OPML

A site that publishes several feeds, or collects other people's, can offer an OPML subscription list, a file that feed readers import to subscribe to every feed at once. serveOpml serves it with the same caching as serveFeed (Cache-Control, a weak ETag, Last-Modified from dateModified, 304 and HEAD), and toOPML returns only the string:

import { serveOpml } from 'hono-feed'

app.get('/subscriptions.opml', (c) =>
  serveOpml(c, {
    title: 'My subscriptions',
    ownerName: 'Ada',
    dateModified: new Date('2026-06-29'),
    outlines: [
      { text: 'Example Blog', xmlUrl: '/feed.xml', htmlUrl: '/' }, // type defaults to "rss"
      {
        text: 'Tech', // an outline with children is a folder
        children: [{ text: 'Another', type: 'atom', xmlUrl: 'https://a.example/atom' }],
      },
    ],
  }),
)

Relative xmlUrl, htmlUrl and ownerId values are resolved against baseUrl (by default the request origin), and every outline needs text. feedExtensionMap maps text/x-opml to .opml, so the route also works with static site generation.

WebSub

WebSub (formerly PubSubHubbub) support has two independent parts: readers can discover your hub, and you can tell the hub about new content.

For discovery, hub on FeedOptions emits rel="hub" links that tell readers where to subscribe (<atom:link rel="hub"> in RSS and Atom, hubs in JSON Feed):

const feed = new Feed({
  title: 'My Blog',
  link: 'https://example.com/',
  hub: 'https://pubsubhubbub.appspot.com/', // or string[] for more than one hub
})

serveFeed also sends the hub and the feed's own URL in an HTTP Link header (<…>; rel="hub", <…>; rel="self"), the header form of WebSub discovery, so hubs and subscribers can find them without parsing the document.

For notification, notifyHub() tells the hub that a feed changed, so subscribers get the update right away instead of at their next poll. WebSub §6 (Publishing) requires the publisher to do this but leaves the method open, so notifyHub sends the PubSubHubbub 0.4 "publish" ping that hubs in practice accept:

import { notifyHub } from 'hono-feed'

const results = await notifyHub(
  'https://pubsubhubbub.appspot.com/', // hub(s) — string or string[]
  'https://example.com/feed.rss', // feed URL(s) that changed — string or string[]
)
// [{ hub: 'https://pubsubhubbub.appspot.com/', ok: true, status: 204 }]

On Cloudflare Workers and other runtimes that stop work once the response is sent, pass the promise to waitUntil. Without it, the request to the hub can be cancelled before it completes:

app.post('/publish', async (c) => {
  await savePost(c)
  c.executionCtx.waitUntil(notifyHub('https://pubsubhubbub.appspot.com/', 'https://example.com/feed.rss'))
  return c.text('ok')
})

notifyHub never rejects. A non-2xx response, a network error and an aborted request (pass { signal } to set a timeout) are all reported in the results, so one unreachable hub can't fail your publishing code. Subscribers still get the update at their next poll.

Pagination

paging on FeedOptions implements RFC 5005 (Feed Paging and Archiving), for a feed too large to send as one document:

const feed = new Feed({
  title: 'My Blog',
  link: 'https://example.com/',
  paging: {
    next: '/feed?page=3', // rel="next"
    prev: '/feed?page=1', // rel="previous" (RFC 5005's term, not "prev")
    first: '/feed?page=1', // rel="first"
    last: '/feed?page=10', // rel="last"
  },
})

RSS 2.0 and Atom 1.0 emit one atom:link or link per field you set. JSON Feed maps only next, to next_url, since the spec has nothing for the others.

paginate() builds those links for you: it slices the items for the current page and returns paging to match. Pass the 1-based page, perPage and a url(page) function. page can be the raw query string value; anything unparsable means page 1, and a page past the end becomes the last page:

import { paginate, serveFeed } from 'hono-feed'

app.get('/feed', (c) => {
  const { items, paging } = paginate(posts, {
    page: c.req.query('page'),
    perPage: 20,
    url: (page) => `/feed?page=${page}`,
  })
  return serveFeed(c, { options: { title: 'My Blog', link: 'https://example.com/', paging }, items })
})

next and prev are set only when that page exists, and first and last whenever there is more than one page. paginate() also returns page and totalPages, in case you'd rather answer an out-of-range page with a 404.

Two more fields cover RFC 5005 §2 and §4. complete (§2) marks a document that contains the entire feed, and archive (§4) marks an archive page whose content never changes, which suits cacheControl: { immutable: true }. They emit <fh:complete/> and <fh:archive/>, with xmlns:fh declared automatically when one is set. They are mutually exclusive, and setting both throws:

paging: {
  archive: true, // this page never changes; safe to cache forever
  current: '/feed', // rel="current": the document that always has the latest entries
  prevArchive: '/archive/2', // rel="prev-archive": the preceding archive page
  nextArchive: '/archive/4', // rel="next-archive": the following archive page
}

prevArchive and nextArchive let a reader walk an archived feed's history page by page, which is what archive pages are for.

Like the rest of paging, complete, archive, current, prevArchive and nextArchive apply to RSS 2.0 and Atom 1.0 only; JSON Feed has nothing to map them to.

RSS channel extras

A few <channel> elements have no equivalent in Atom or JSON Feed, so they are plain FeedOptions fields outside the shared model. Like language and copyright, they work in every <rss version="…"> structure (0.91 through 2.0):

const feed = new Feed({
  title: 'My Blog',
  link: 'https://example.com/',
  webmaster: { name: 'Ada', email: 'webmaster@example.com' }, // <webMaster>: email required, like author
  docs: true, // <docs>: true emits the RSS 2.0 spec URL; a string is emitted as-is
  skipHours: [0, 1, 2], // <skipHours><hour>…</hour></skipHours>: GMT hours (0–23) readers can skip
  skipDays: ['Saturday', 'Sunday'], // <skipDays><day>…</day></skipDays>
})

On an item, source records the feed the entry was republished from: <source url="…">Title</source> in RSS 2.0, and <source> with a title and a rel="self" link (RFC 4287 §4.2.11) in Atom 1.0. Both title and url, the URL of the original feed, are required. JSON Feed has no equivalent:

feed.addItem({
  title: 'A post worth sharing',
  link: 'https://example.com/shared',
  source: { title: 'Original Blog', url: 'https://original.example/feed.xml' },
})

skipHours values outside 0–23 throw. textInput and cloud (rssCloud) are not modeled on purpose: textInput is hardly used, and WebSub (above) has replaced cloud in practice. Use customXml if you need either.

Media RSS

media on a FeedItem adds Media RSS thumbnails and media objects, the de facto standard for attaching a preview image or a video to an RSS or Atom entry. xmlns:media is declared automatically, and only when an item sets media; a customNamespaces entry takes precedence.

feed.addItem({
  title: 'New video',
  link: 'https://example.com/video',
  media: {
    thumbnails: [{ url: '/video-thumb.jpg', width: 320, height: 180 }], // <media:thumbnail>
    contents: [{ url: '/video.mp4', type: 'video/mp4', medium: 'video', duration: 42 }], // <media:content>
  },
})

URLs are resolved against baseUrl like every other URL field, and every entry needs a url. Only RSS 2.0 and Atom 1.0 emit it; JSON Feed has no equivalent, so use the item's image there.

Set itemImageAsThumbnail: true in the feed options to also emit each item's image as a <media:thumbnail> in RSS 2.0 and Atom 1.0, so readers that only look at Media RSS still show a preview. An item that sets media.thumbnails keeps its own and gets no extra one. Without the option, image stays JSON Feed-only.

Extra links

links on FeedOptions and FeedItem adds links that no dedicated field covers: a related page, the original source (via), a license (RFC 4946) or a version in another language. Each entry becomes a <link> in Atom 1.0 or an <atom:link> in RSS 2.0. JSON Feed has no equivalent, and the other versions ignore them.

feed.addItem({
  title: 'Bonjour',
  link: 'https://example.com/fr/bonjour',
  links: [
    { rel: 'alternate', href: '/en/hello', hreflang: 'en', type: 'text/html' },
    { rel: 'via', href: 'https://origin.example/post' },
  ],
})

Entries are { rel, href, type?, hreflang?, title?, length? }, and href is resolved against baseUrl. Both rel and href are required. Relations that already have a field (self, hub, enclosure, replies, and the paging ones) throw, so a link is never emitted twice. In Atom, a rel: 'alternate' link must also differ in type or hreflang from every other alternate link, including the one built from link (which has neither) (RFC 4287 §4.1.1).

Extending with custom fields

The shared model is deliberately small. For anything outside it, such as extra Dublin Core elements, a namespaced module hono-feed doesn't model, or custom JSON Feed keys, use customXml and customNamespaces (XML formats) or customJson (JSON Feed). They are available on both FeedOptions (feed level) and FeedItem (item level):

const feed = new Feed({
  title: 'My Show',
  link: 'https://example.com/',
  customNamespaces: { 'xmlns:dcterms': 'http://purl.org/dc/terms/' },
  customXml: [{ name: 'dcterms:license', text: 'https://creativecommons.org/licenses/by/4.0/' }],
})

customXml is an element tree ({ name, attrs?, children?, text? }), not a raw string, and text and attrs are escaped like every built-in element, so the output stays well-formed. The elements are appended after the built-in children of <channel>/<feed> or <item>/<entry>. RSS 0.91 through 2.0, RSS 1.0/1.1 and Atom 1.0 emit them whatever the version, because adding them is an explicit choice; RSS 0.90 and Atom 0.3 ignore them. customNamespaces adds xmlns:* declarations to the root element.

customJson merges extra keys into the JSON Feed object, at the feed level, per item, or both. The JSON Feed spec says custom keys should start with _. A built-in key always wins on a collision, so this can add fields but never override one hono-feed sets.

Low-level serializers

For a snapshot test, a queue, or a transport other than Hono, you may want only the string. toRSS, toAtom and toJSONFeed return it without any HTTP handling:

import { toRSS, toAtom, toJSONFeed } from 'hono-feed'

// For a smaller bundle, import one from 'hono-feed/rss', 'hono-feed/atom' or 'hono-feed/json' instead.

const xml = toRSS({ options, items }, { baseUrl: 'https://example.com' })

serveFeed checks each format's spec requirements (an Atom author, absolute IRI ids, required dates, …) before serializing. The serializers don't, so call validateInput first if you want the same checks:

import { toAtom, validateInput } from 'hono-feed'

validateInput({ options, items }, 'atom') // throws TypeError with the same messages serveFeed gives
const xml = toAtom({ options, items }, { baseUrl: 'https://example.com' })

Linting

validateInput rejects only what would break the document, such as a missing title or a missing Atom author. lintInput also flags fields that the spec makes optional but readers and directories expect: a missing feed description, language or image, an item without an id, author or date, incomplete podcast metadata when podcast is set, and so on. It catches common mistakes too: duplicate item ids, a date in the future (usually a time zone mix-up), relative URLs left in content or description, an enclosure without type or length, an overlong title or one containing HTML, and more than 100 items without paging.

lintInput never throws. It returns the warnings as a string[], empty when there are none. serveFeed doesn't call it; it's meant for tests and CI:

import { lintInput } from 'hono-feed'

const warnings = lintInput({ options, items }, 'rss')
// e.g. expect(lintInput({ options, items }, 'rss')).toEqual([]) in a CI check

Every rule has an id (LintRuleId), so you can turn off the ones you accept: lintInput(input, 'rss', { ignore: ['feed-language', 'item-count'] }). The future-date rule compares against the current time; pass now to make a test deterministic.

Contributing

Contributions are welcome. You can help in these ways:

  • Open an issue to propose a feature or report a bug.
  • Send a pull request to fix a bug or a typo, or to refactor code.
  • Share your thoughts on a blog, Twitter or elsewhere.
  • Build something with hono-feed.

For more details, see CONTRIBUTING.md.

Contributors

Thanks to all contributors!

Authors

otoneko. https://github.com/otnc

License

Distributed under the MIT License. See LICENSE for more information.

About

RSS, Atom and JSON Feed for Hono — done right.

Topics

Resources

Contributing

Stars

30 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages