npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

ts-caldav

v0.4.0

Published

A CalDAV client written in TypeScript

Readme

ts-caldav

npm version Run Tests

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

  • 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 getctag and etag
  • Efficient sync with diff-based updates
  • Unified error handling via a single CalDAVError type
  • Built for TypeScript, with full type safety

Installation

npm install ts-caldav
# or
pnpm install ts-caldav
# or
yarn add ts-caldav

Requirements: 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 fetch became a global)
  • modern browsers
  • React Native (fetch/AbortController are built in)
  • edge runtimes — Cloudflare Workers, Deno, Bun, Vercel Edge

The engines.node field (>=18) only constrains Node itself and does not restrict browser, React Native, or edge deployments. The optional undici fallback for rejectUnauthorized: false is Node-only and loaded lazily, so it never affects other runtimes. (Basic auth relies on btoa; on older React Native versions without it, add a small btoa polyfill 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: false and native fetch: ts-caldav uses the runtime's built-in fetch, which has no per-request TLS toggle. To disable certificate verification in Node.js, install undici (npm i undici) — ts-caldav will use it automatically — or set the NODE_TLS_REJECT_UNAUTHORIZED=0 environment 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 updateEvent on strict CalDAV servers may fail unless the ETag is retrieved via PROPFIND. Use getETag() 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:

  • changed
  • newCtag
  • newEvents
  • updatedEvents
  • deletedEvents

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:

  • changed
  • newCtag
  • newTodos
  • updatedTodos
  • deletedTodos

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 getctag plus ETag diffing.
  • Component support is currently focused on VEVENT and VTODO.

Roadmap

  • Add deterministic mocked request fixtures for common server response shapes.
  • Add WebDAV sync-token support with getctag diffing as a fallback.
  • Expand component support after the VEVENT and VTODO APIs 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 test

Contributing

Contributions welcome! See CONTRIBUTING.

License

This project is licensed under the MIT License. See the LICENSE file for details.