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.
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#
- On the server, load a team's events and return
toICS(events)with thetext/calendarcontent type. - In the browser, fetch external feeds in an
eventSourceand convert them withparseICS(). - For file imports, merge parsed events by
id, which comes from the iCalendarUID.
Publish a feed#
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 useVALUE=DATE. - Series keep their
RRULEandEXDATEs. Detached occurrences, the events withrecurrenceIdandrecurringEventId, are written asRECURRENCE-IDoverrides under the master'sUID, so moved visits show up correctly. description,location,url,statusandcategoriesare 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:
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 { 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 byUID. Use your database id as the eventid; 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.
VTIMEZONEblocks 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.