Birch UI v0.1
Pricing

Publish and subscribe to iCalendar feedsCalendar

Serve a team's events as a subscribable .ics feed with toICS, show external feeds in the Event Calendar with parseICS, and import .ics files without duplicates.

Open .md

Technicians want their visits in the calendar app on their phone, and the office wants public holidays and supplier schedules next to its own events. This recipe publishes a feed URL that Outlook, Google Calendar and Apple Calendar can subscribe to, shows external feeds in the Event Calendar, and imports .ics files without creating duplicates.

Steps#

  1. On the server, load a team's events and return toICS(events) with the text/calendar content type.
  2. In the browser, fetch external feeds in an eventSource and convert them with parseICS().
  3. For file imports, merge parsed events by id, which comes from the iCalendar UID.

Publish a feed#

server/calendar-feed.ts
import { toICS, type IcsEvent } from '@birchui/calendar';

app.get('/feeds/teams/:teamId/:token.ics', async (request, response) => {
  const team = await db.teams.findByFeedToken(request.params.teamId, request.params.token);
  if (!team) return response.status(404).end();

  const visits = await db.visits.forTeam(team.id, { from: monthsAgo(3), to: monthsAhead(12) });
  const events: IcsEvent[] = visits.map((visit) => ({
    id: visit.id,
    title: `${visit.jobType}: ${visit.customerName}`,
    start: visit.start,
    end: visit.end,
    timeZone: team.timeZone,
    location: visit.siteAddress,
    description: `Work order ${visit.workOrderNo}\nAccess: ${visit.accessNotes ?? 'none'}`,
    status: visit.cancelled ? 'CANCELLED' : 'CONFIRMED',
    rrule: visit.rrule ?? undefined,
    exdates: visit.exdates ?? undefined,
    recurrenceId: visit.recurrenceId ?? undefined,
    recurringEventId: visit.seriesId ?? undefined,
  }));

  response
    .type('text/calendar; charset=utf-8')
    .set('Cache-Control', 'private, max-age=900')
    .send(toICS(events, { calendarName: `${team.name} visits` }));
});

Users add the URL in their calendar app as a subscription (in Outlook: Add calendar › Subscribe from web; in Google Calendar: Other calendars › From URL). Apps refresh subscriptions on their own schedule, typically every few hours.

How toICS writes events:

  • Zoned events get a TZID, UTC instants are written in UTC, all-day events use VALUE=DATE.
  • Series keep their RRULE and EXDATEs. Detached occurrences, the events with recurrenceId and recurringEventId, are written as RECURRENCE-ID overrides under the master's UID, so moved visits show up correctly.
  • description, location, url, status and categories are written; your other fields are not.

Show an external feed#

An eventSource is called with the visible range. Fetch the feed, parse it and return the events:

team-calendar.ts
import { createCalendar, parseICS, type EventSourceRequest } from '@birchui/calendar';

const FEEDS = ['/feeds/proxy/uk-bank-holidays.ics', '/feeds/proxy/supplier-deliveries.ics'];

async function loadFeeds({ signal }: EventSourceRequest) {
  const [ownVisits, ...external] = await Promise.all([
    fetch('/api/visits', { signal }).then((r) => r.json()),
    ...FEEDS.map((url) =>
      fetch(url, { signal })
        .then((r) => (r.ok ? r.text() : ''))
        .then((text) => parseICS(text).map((event) => ({ ...event, editable: false, color: 'slategray' }))),
    ),
  ]);
  return [...ownVisits, ...external.flat()];
}

const calendar = createCalendar(document.querySelector<HTMLElement>('#team-calendar')!, {
  view: 'month',
  timeZone: 'Europe/London',
  eventSource: loadFeeds,
});

Most calendar providers do not send CORS headers, so fetch third-party feeds through a small proxy on your own server, as the /feeds/proxy/ URLs above do.

Import a file without duplicates#

parseICS() sets each event's id from its UID, and detached occurrences get '<UID>@<recurrence id>'. Importing the same file twice therefore produces the same ids. Merge by id instead of appending:

import-ics.ts
import { parseICS } from '@birchui/calendar';

async function importIcsFile(file: File) {
  const imported = parseICS(await file.text());
  const byId = new Map(calendar.getEvents().map((event) => [String(event.id), event]));
  let added = 0;
  for (const event of imported) {
    if (!byId.has(String(event.id))) added += 1;
    byId.set(String(event.id), event);
  }
  calendar.setEvents([...byId.values()]);
  statusLine.textContent = `${added} new and ${imported.length - added} updated events from ${file.name}`;
}

With an eventSource, send the parsed events to your server instead and call calendar.refetch().

Pitfalls#

  • Keep UIDs stable. Calendar apps match events by UID. Use your database id as the event id; never generate a new one per request, or subscribers see every event twice after a refresh.
  • Protect private feeds. Subscription URLs cannot send cookies or headers, so put an unguessable token in the URL and let users reset it.
  • Time zones. VTIMEZONE blocks are not written or read; zones are referred to by IANA name, which the major calendar apps resolve. Windows zone names in Outlook files are mapped to IANA names on import.
  • Custom fields. Only standard properties survive a round trip. Keep the rest in your database keyed by id.

↑ ↓ to move, Enter to open, Esc to close