ts-caldav
v0.4.0
Published
A CalDAV client written in TypeScript
Maintainers
Readme
ts-caldav
A lightweight, promise-based TypeScript CalDAV client for syncing calendar data in browser, Node.js, or React Native environments.
ts-caldav helps you interact with CalDAV servers, allowing you to fetch calendars, manage events (including recurring events), and synchronize changes with minimal effort. Great for building calendar apps or integrations.
Table of Contents
- Features
- Installation
- Quick Start
- Known Working Servers
- API Documentation
- Timezone Support
- Recurrence Support
- Error Handling
- Auth Notes
- Example: Sync Local Calendar
- Limitations
- Roadmap
- Development
- Contributing
- License
Features
- Credential validation with CalDAV servers
- Automatic CalDAV endpoint discovery
- Fetch calendar homes and individual calendars (with color support)
- List, create (including recurring), update, and delete events and todos (VTODO)
- Optional server-side expansion of recurring events into individual occurrences
- Detect changes using
getctagandetag - Efficient sync with diff-based updates
- Unified error handling via a single
CalDAVErrortype - Built for TypeScript, with full type safety
Installation
npm install ts-caldav
# or
pnpm install ts-caldav
# or
yarn add ts-caldavRequirements: ts-caldav bundles no HTTP-client dependency — it uses the runtime's built-in web APIs (
fetch,AbortController,URL,btoa). It therefore runs on any runtime that provides them, including:
- Node.js 18+ (where
fetchbecame a global)- modern browsers
- React Native (
fetch/AbortControllerare built in)- edge runtimes — Cloudflare Workers, Deno, Bun, Vercel Edge
The
engines.nodefield (>=18) only constrains Node itself and does not restrict browser, React Native, or edge deployments. The optionalundicifallback forrejectUnauthorized: falseis Node-only and loaded lazily, so it never affects other runtimes. (Basic auth relies onbtoa; on older React Native versions without it, add a smallbtoapolyfill or use OAuth.)
Quick Start
import { CalDAVClient } from "ts-caldav";
const client = await CalDAVClient.create({
baseUrl: "https://caldav.example.com",
auth: {
type: "basic",
username: "myuser",
password: "mypassword",
}
});
// List calendars
const calendars = await client.getCalendars();
// Fetch events
const events = await client.getEvents(calendars[0].url);Known Working Servers
| Provider | Endpoint Example |
|:--------------|:------------------|
| Google | https://apidata.googleusercontent.com/ |
| iCloud | https://caldav.icloud.com/ |
| Yahoo | https://caldav.calendar.yahoo.com |
| GMX | https://caldav.gmx.net |
| Fastmail | https://caldav.fastmail.com |
| Nextcloud | https://your-host/remote.php/dav |
| Baikal | https://your-host (or https://your-host/dav.php) |
| Radicale | https://your-host |
Note: Some servers may require enabling CalDAV support or generating app-specific passwords, especially iCloud and Fastmail.
API Documentation
CalDAVClient.create(options)
Creates and validates a new CalDAV client instance.
const client = await CalDAVClient.create({
baseUrl: "https://caldav.example.com",
auth: {
type: "basic",
username: "john",
password: "secret",
},
logRequests: true,
});Options
| Option | Type | Default | Description |
| -------------------- | --------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------- |
| baseUrl | string | — | Base URL of the CalDAV server. Required. |
| auth | { type: "basic", ... } | { type: "oauth", accessToken } | — | Credentials. Required. |
| requestTimeout | number (ms) | 5000 | Aborts a request after this many milliseconds. Set 0 to disable. |
| logRequests | boolean | false | Logs each request method, URL, and response status via console.debug. |
| prodId | string | ts-caldav default | PRODID written into generated iCalendar data. |
| headers | Record<string, string> | {} | Extra headers merged into every request. |
| rejectUnauthorized | boolean | true | Set false to allow self-signed / invalid TLS certificates. See the note below. |
rejectUnauthorized: falseand nativefetch: ts-caldav uses the runtime's built-infetch, which has no per-request TLS toggle. To disable certificate verification in Node.js, installundici(npm i undici) — ts-caldav will use it automatically — or set theNODE_TLS_REJECT_UNAUTHORIZED=0environment variable. If neither is available the option can't take effect and a warning is logged rather than failing silently. Only use this against servers you control.
CalDAVClient.createFromCache(options, cache)
Restores a client from cached state without re-fetching calendar home or validating credentials.
const cache = client.exportCache();
const restored = await CalDAVClient.createFromCache({
baseUrl: "https://caldav.example.com",
auth: {
type: "basic",
username: "john",
password: "secret",
}
}, cache);getCalendars(): Promise<Calendar[]>
Returns an array of available calendars.
getEvents(calendarUrl: string, options?): Promise<Event[]>
Fetches events within a given time range (defaults to 3 weeks ahead). When all is true and no range is provided, fetches all events.
const events = await client.getEvents(calendarUrl, {
start: new Date(),
end: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
all: false
});Pass expand: true (only valid together with a start/end range) to have the
server expand recurring events into their individual occurrences instead of
returning the master event with its recurrence rule:
const occurrences = await client.getEvents(calendarUrl, {
start: new Date(),
end: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
expand: true,
});The same options (including expand) apply to getTodos.
createEvent(calendarUrl, eventData)
Supports full-day, recurring, and timezone-aware events.
await client.createEvent(calendar.url, {
summary: "Team Sync",
start: new Date("2025-07-01T09:00:00"),
end: new Date("2025-07-01T10:00:00"),
startTzid: "Europe/Berlin",
endTzid: "Europe/Berlin",
status: "CONFIRMED",
alarms: [
{ action: "DISPLAY", trigger: "-PT30M", description: "Popup reminder" },
{ action: "AUDIO", trigger: "-PT15M" },
{
action: "EMAIL",
trigger: "-PT10M",
summary: "Email Reminder",
description: "Meeting coming up",
attendees: ["mailto:[email protected]"],
},
],
});If startTzid/endTzid omitted, event stored in UTC.
To use full timezone definitions, include your own VTIMEZONE in raw iCal.
ETag notice: Some CalDAV servers, such as Yahoo, do not return an ETag header when creating events. Because ETag is required to safely update events, calling
updateEventon strict CalDAV servers may fail unless the ETag is retrieved via PROPFIND. UsegetETag()to fetch it manually.
deleteEvent(calendarUrl, eventUid, etag?)
Delete by UID, optionally using ETag for safe deletion.
syncChanges(calendarUrl, previousCtag, localEventRefs)
Compares remote state using getctag/etag and returns:
changednewCtagnewEventsupdatedEventsdeletedEvents
getEventsByHref(calendarUrl, hrefs)
Fetch .ics data for specific events.
getETag(href)
Fetch the current ETag for an event.
const etag = await client.getETag("/calendars/user/calendar-id/event-id.ics");
await client.updateEvent(calendarUrl, {
uid: "event-id",
href: "/calendars/user/calendar-id/event-id.ics",
etag,
summary: "Updated summary",
start: new Date(),
end: new Date(Date.now() + 60 * 60 * 1000),
});Automatically strips weak validator prefixes (e.g.,
W/"...").
Todo API
getTodos(calendarUrl: string, options?): Promise<Todo[]>
Fetches todos within a given range or all.
getTodosByHref(calendarUrl: string, hrefs: string[]): Promise<Todo[]>
Fetches full .ics data for specific todos.
createTodo(calendarUrl: string, todoData)
Creates a new todo.
await client.createTodo(calendar.url, {
summary: "Buy groceries",
due: new Date("2025-08-12T18:00:00"),
alarms: [{ action: "DISPLAY", trigger: "-PT1H", description: "Reminder" }]
});updateTodo(calendarUrl: string, todo)
Updates an existing todo.
deleteTodo(calendarUrl: string, todoUid, etag?)
Deletes a todo by UID.
syncTodoChanges(calendarUrl, previousCtag, localTodoRefs)
Compares remote todo list state with local references using getctag and etag.
Returns:
changednewCtagnewTodosupdatedTodosdeletedTodos
Timezone Support
await client.createEvent(calendar.url, {
summary: "Flight to SF",
start: new Date("2025-07-01T15:00:00"),
end: new Date("2025-07-01T18:00:00"),
startTzid: "Europe/Berlin",
endTzid: "America/Los_Angeles",
});When fetching, startTzid/endTzid will be parsed for correct interpretation and normalization.
Recurrence Support
Supports freq, interval, count, until, byday, bymonthday, bymonth.
recurrenceRule: {
freq: "MONTHLY",
interval: 1,
byday: ["FR"],
until: new Date("2025-12-31"),
}Error Handling
Every failure thrown from a public method is a CalDAVError. It exposes an
optional status (the HTTP status code, when the failure came from a response)
and, for wrapped lower-level failures, the original error as cause.
import { CalDAVClient, CalDAVError } from "ts-caldav";
try {
await client.getEvents(calendarUrl);
} catch (err) {
if (err instanceof CalDAVError) {
console.error(err.message, err.status); // e.g. "HTTP 404", 404
console.error(err.cause); // underlying error, if any
}
}Request timeouts and network failures are wrapped in CalDAVError too, so a
single catch is enough.
Auth Notes
- Basic Auth & OAuth2 supported
- Works with Google, iCloud, Fastmail, Nextcloud, Radicale
Example Use Case: Sync Local Calendar
const result = await client.syncChanges(calendar.url, lastCtag, localEventRefs);
if (result.changed) {
const newEvents = await client.getEventsByHref(calendar.url, [
...result.newEvents,
...result.updatedEvents,
]);
updateLocalDatabase(newEvents, result.deletedEvents);
saveNewCtag(result.newCtag);
}Limitations
- No WebDAV sync-token support yet; synchronization currently uses
getctagplus ETag diffing. - Component support is currently focused on
VEVENTandVTODO.
Roadmap
- Add deterministic mocked request fixtures for common server response shapes.
- Add WebDAV sync-token support with
getctagdiffing as a fallback. - Expand component support after the
VEVENTandVTODOAPIs are stable. - Continue hardening provider compatibility for Google, iCloud, Nextcloud, Fastmail, and Radicale.
Development
git clone https://github.com/KlautNet/ts-caldav.git
cd ts-caldav
pnpm install
pnpm build
pnpm testContributing
Contributions welcome! See CONTRIBUTING.
License
This project is licensed under the MIT License. See the LICENSE file for details.
