# Import and Export

Read .ics files from Google Calendar, Apple Calendar and Outlook, write events back out, and sync with Google Calendar.

Live example, interactive at https://calendarcn.xyz/docs/import-export. Its source:

```tsx title="src/examples/ics-demo.tsx"
"use client";

import * as React from "react";
import { startOfWeek } from "date-fns";
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  DownloadIcon,
  UploadIcon,
} from "lucide-react";

import { CalendarProvider, useCalendar } from "@/components/calendar-provider";
import { WeekView } from "@/components/week-view";
import { Button } from "@/components/ui/button";
import type { DetailedCalendarEvent } from "@/components/calendar-types";
import { parseIcs, toIcs } from "@/lib/ics";
import { createSampleEvents } from "@/lib/sample-events";

/** File types the import picker offers */
const ICS_FILE_TYPES = ".ics,text/calendar";

/** Name of the downloaded file */
const EXPORT_FILE_NAME = "calendar.ics";

/** Status line shown until the first import */
const IMPORT_HINT = "Drop an .ics file on the calendar, or use Import.";

export function IcsDemo() {
  const [events, setEvents] = React.useState<DetailedCalendarEvent[]>(() =>
    createSampleEvents(new Date()),
  );

  // Imported events replace the ones with the same id (importing a file
  // twice updates it) and are added next to the others
  const importEvents = React.useCallback(
    (imported: DetailedCalendarEvent[]) => {
      const importedIds = new Set(imported.map((event) => event.id));
      setEvents((current) => [
        ...current.filter((event) => !importedIds.has(event.id)),
        ...imported,
      ]);
    },
    [],
  );

  return (
    <CalendarProvider events={events} onEventsChange={setEvents}>
      <IcsCalendar events={events} onImport={importEvents} />
    </CalendarProvider>
  );
}

interface IcsCalendarProps {
  events: DetailedCalendarEvent[];
  onImport: (events: DetailedCalendarEvent[]) => void;
}

function IcsCalendar({ events, onImport }: IcsCalendarProps) {
  const {
    monthName,
    year,
    weekStartsOn,
    goToToday,
    goToPrev,
    goToNext,
    goToDate,
  } = useCalendar();
  const fileInputRef = React.useRef<HTMLInputElement>(null);
  const [status, setStatus] = React.useState(IMPORT_HINT);
  const [isDraggingFile, setIsDraggingFile] = React.useState(false);

  const importFile = async (file: File) => {
    const imported = parseIcs(await file.text());
    if (imported.length === 0) {
      setStatus(`No events found in ${file.name}.`);
      return;
    }

    onImport(imported);
    // Jump to the week of the earliest imported event (a repeating event's
    // first date)
    const earliest = imported.reduce((first, event) =>
      event.start < first.start ? event : first,
    );
    goToDate(startOfWeek(earliest.start, { weekStartsOn }));
    const noun = imported.length === 1 ? "event" : "events";
    setStatus(`Imported ${imported.length} ${noun} from ${file.name}.`);
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    // Clear the input so picking the same file again imports it again
    event.target.value = "";
    if (file) void importFile(file);
  };

  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setIsDraggingFile(false);
    const file = event.dataTransfer.files[0];
    if (file) void importFile(file);
  };

  return (
    <div className="flex h-full flex-col">
      <header className="flex flex-wrap items-center gap-2 border-b px-3 py-2">
        <h2 className="min-w-0 flex-1 truncate text-base font-semibold">
          {monthName} {year}
        </h2>
        <Button variant="secondary" size="sm" onClick={goToToday}>
          Today
        </Button>
        <div className="flex items-center">
          <Button
            variant="ghost"
            size="icon-sm"
            aria-label="Previous week"
            onClick={goToPrev}
          >
            <ChevronLeftIcon />
          </Button>
          <Button
            variant="ghost"
            size="icon-sm"
            aria-label="Next week"
            onClick={goToNext}
          >
            <ChevronRightIcon />
          </Button>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={() => fileInputRef.current?.click()}
        >
          <UploadIcon />
          Import .ics
        </Button>
        <Button variant="outline" size="sm" onClick={() => downloadIcs(events)}>
          <DownloadIcon />
          Export .ics
        </Button>
        <input
          ref={fileInputRef}
          type="file"
          accept={ICS_FILE_TYPES}
          aria-label="Import .ics file"
          className="hidden"
          onChange={handleFileChange}
        />
      </header>
      <p
        role="status"
        className="truncate border-b px-3 py-1.5 text-xs text-muted-foreground"
      >
        {status}
      </p>
      <div
        className="relative min-h-0 flex-1"
        onDragEnter={(event) => {
          if (event.dataTransfer.types.includes("Files")) {
            setIsDraggingFile(true);
          }
        }}
      >
        <WeekView scrollToHour={8} />
        {/* Covers the calendar while a file is dragged over it, so the
            calendar's own pointer handlers never see the drag */}
        {isDraggingFile && (
          <div
            data-testid="ics-drop-zone"
            className="absolute inset-0 z-40 flex items-center justify-center bg-background/80 p-3"
            onDragOver={(event) => {
              event.preventDefault();
              event.dataTransfer.dropEffect = "copy";
            }}
            onDragLeave={() => setIsDraggingFile(false)}
            onDrop={handleDrop}
          >
            <div className="pointer-events-none flex size-full items-center justify-center rounded-lg border-2 border-dashed border-primary/40 text-sm font-medium">
              Drop the .ics file to import it
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/** Downloads the events as an .ics file */
function downloadIcs(events: DetailedCalendarEvent[]) {
  const ics = toIcs(events, { calendarName: "CalendarCN" });
  const url = URL.createObjectURL(
    new Blob([ics], { type: "text/calendar;charset=utf-8" }),
  );
  const link = document.createElement("a");
  link.href = url;
  link.download = EXPORT_FILE_NAME;
  link.click();
  // Revoke after the click has started the download
  setTimeout(() => URL.revokeObjectURL(url), 0);
}
```

`parseIcs()` turns an iCalendar (`.ics`) file into events the calendar draws, and `toIcs()` turns events into a file other calendars import. Both live in one file with no dependencies beyond `date-fns`. In the preview, import a file with **Import .ics** or drop it on the calendar, then download every event with **Export .ics**.

To get a file to try: in Google Calendar, open **Settings → Import & export → Export**. In Apple Calendar, choose **File → Export → Export…**. In Outlook, choose **File → Save Calendar**.

## Installation

```bash
npx shadcn add @calendarcn/ics
```

Or install it by hand:

1. Install the items it builds on: `@calendarcn/calendar-core`
2. Install the dependencies: `npm install date-fns`
3. Copy these files into your project, keeping the paths under your components, hooks and lib folders:
   - [`lib/ics.ts`](https://github.com/vmnog/calendarcn/blob/main/src/lib/ics.ts)

## Import a file

Read the file as text and pass it to `parseIcs()`. It returns `DetailedCalendarEvent[]`, ready for the provider.

```tsx
import { parseIcs } from "@/lib/ics";

async function importFile(file: File) {
  const imported = parseIcs(await file.text());
  setEvents((events) => [...events, ...imported]);
}

<input
  type="file"
  accept=".ics,text/calendar"
  onChange={(event) => {
    const file = event.target.files?.[0];
    if (file) void importFile(file);
  }}
/>;
```

Each event keeps the file's `UID` as its `id`. The preview uses that to replace events it already has, so importing the same file twice doesn't duplicate them.

To add a file as a calendar of its own, as the live demo's "Add calendar account" does, pass its events to `toIcsCalendar()` with the file's name and your calendars. It returns a calendar named after the file and the events on it; the same file again returns the same calendar:

```ts
import { parseIcs, toIcsCalendar } from "@/lib/ics";

const { calendar, events } = toIcsCalendar(
  file.name,
  parseIcs(await file.text()),
  calendars,
);
```

### What gets imported

| iCalendar                        | Event field                                                                                                  |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `UID`                            | `id`. An edited occurrence of a recurring event gets `<UID>-<yyyy-MM-dd>`, the id of that date's occurrence. |
| `SUMMARY`                        | `title`                                                                                                      |
| `DTSTART`, `DTEND` or `DURATION` | `start`, `end` and `isAllDay`                                                                                |
| `DESCRIPTION`, `LOCATION`        | `description`, `location`                                                                                    |
| `RRULE`                          | `recurrenceRule`, e.g. `FREQ=WEEKLY;BYDAY=MO` to a weekly rule on Mondays                                    |
| `EXDATE`                         | `excludedDates`                                                                                              |
| `RECURRENCE-ID`                  | `originalStart` of an edited occurrence, with the series' `UID` as `seriesId`                                |
| `TRANSP`                         | `status`: `TRANSPARENT` is free, `OPAQUE` is busy                                                            |
| `CLASS`                          | `visibility`: public, or private for `PRIVATE` and `CONFIDENTIAL`                                            |
| `COLOR`                          | `color`, when it names one of the seven event colors                                                         |
| `VALARM`                         | `reminders`, for alarms set a fixed time before the start. See **Reminders**                                 |

Dates and times follow RFC 5545:

- **All-day events.** DATE values (`20260603`) become all-day events. iCalendar's end date is exclusive and the calendar's `end` is the last day, so an event from `20260603` to `20260604` becomes a one-day event on June 3.
- **Times.** Times in UTC (`20260603T150000Z`), with a `TZID`, and floating times (no zone) all become `Date`s, shown in the calendar's time zone (the viewer's unless the provider sets `timeZone`). A `TZID` can be an IANA name, as Google and Apple write it, or a zone the file defines in a `VTIMEZONE`, such as Outlook's `Pacific Standard Time`. Floating times are read in the viewer's zone. A repeating event keeps an IANA `TZID` as its `timeZone`, and its rule is read in that zone.
- **Text.** Folded lines are joined and escaped commas, semicolons and line breaks are restored.
- **Reminders.** A `VALARM` set a fixed time before the start (`TRIGGER:-PT15M`) becomes a reminder in its largest whole unit, and `-P1W` in weeks. On an all-day event, an alarm that isn't a whole number of days is a day and a time of day: Apple's `-PT15H` is 1 day before at 9 AM. Alarms after the start, relative to the end or at a fixed date are skipped.

> **Recurring events**
>
> A weekly meeting comes in as one event with its rule in `recurrenceRule`, and the views draw it on every date. A rule `recurrenceRule` can't hold exactly (`BYMONTHDAY=1,15`, `BYHOUR`, a fifth weekday of the month, ...) is kept as written in `recurrence`, reads "Custom repeat" and draws once. An edited occurrence comes in as its own event with `seriesId` and `originalStart` and takes its date's place; a cancelled one becomes an `excludedDates` entry of its series. Attendees and the organizer come in as `participants`: their name (`CN`), response (`PARTSTAT`), `optional` (`ROLE=OPT-PARTICIPANT`) and `organizer`, and `toIcs()` writes them back. iCalendar doesn't say which attendee you are, so `toIcs()` marks the participant with `self: true` with a `X-CALENDARCN-SELF=TRUE` parameter that other apps ignore, and `parseIcs()` reads it back. Rooms and equipment (`CUTYPE=ROOM` or `RESOURCE`), attachments, to-dos (`VTODO`) and other components are skipped.

## Export events

`toIcs()` returns the file's text. Download it with a blob URL, or send it from your server with the `text/calendar` content type.

```tsx
import { toIcs } from "@/lib/ics";

function downloadIcs(events: DetailedCalendarEvent[]) {
  const ics = toIcs(events, { calendarName: "Team" });
  const url = URL.createObjectURL(
    new Blob([ics], { type: "text/calendar;charset=utf-8" }),
  );
  const link = document.createElement("a");
  link.href = url;
  link.download = "calendar.ics";
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 0);
}
```

Timed events are written in UTC and all-day events as dates, with the exclusive end iCalendar expects. A repeating timed event is written as clock time with a `TZID` instead (its `timeZone`, else the viewer's zone), so other calendars keep it at the same clock time when the clocks change. `recurrenceRule` is written as an `RRULE`, its end date as an `UNTIL` at the end of that day in the event's time zone. Without one, `recurrence` is written only when it holds a rule (`FREQ=...`), so a display string such as "Every weekday" is left out. `excludedDates` are written as `EXDATE`, and an edited occurrence as a `VEVENT` with its series' `UID`, a `RECURRENCE-ID` and no rule, in the series' zone. Each reminder becomes a `VALARM` with a trigger before the start: `-PT10M`, `-PT2H`, `-P1D`, and weeks as `-P1W`. An all-day reminder with a `time` is written in minutes from the event's midnight start: 1 day before at 9 AM is `-PT900M`, and on the day at 9 AM is `PT540M`. `parseIcs()` reads each one back the same. Long lines are folded at 75 octets and lines end with CRLF, so Google Calendar, Apple Calendar and Outlook all import the file.

## Sync with Google Calendar

> **A recipe, not a live demo**
>
> This needs your own Google Cloud project and OAuth client, so it has no preview. Treat it as a starting point: add error handling, paging (`nextPageToken`) and token refresh before you ship it.

The Google Calendar API stays the source of truth. The calendar loads the events of the days on screen, and writes each change back.

### Get an access token

In the [Google Cloud console](https://console.cloud.google.com/), enable the Google Calendar API and create an OAuth client ID of type "Web application", with your site as an authorized JavaScript origin. Then request a token for the `calendar.events` scope with [Google Identity Services](https://developers.google.com/identity/oauth2/web/guides/use-token-model):

```tsx
// Load https://accounts.google.com/gsi/client first
const tokenClient = google.accounts.oauth2.initTokenClient({
  client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
  scope: "https://www.googleapis.com/auth/calendar.events",
  callback: (response) => setAccessToken(response.access_token),
});

// From a click, so the browser allows the consent popup
tokenClient.requestAccessToken();
```

### Map Google events to calendar events

Google writes all-day events as dates with an exclusive end, like iCalendar, and timed events as ISO strings.

```ts
import { addDays, format, parseISO, subDays } from "date-fns";

import type { DetailedCalendarEvent } from "@/components/calendar-types";

interface GoogleEvent {
  id: string;
  summary?: string;
  description?: string;
  location?: string;
  start: { date?: string; dateTime?: string };
  end: { date?: string; dateTime?: string };
  transparency?: "opaque" | "transparent";
}

function fromGoogle(event: GoogleEvent): DetailedCalendarEvent {
  const details: Omit<DetailedCalendarEvent, "start" | "end"> = {
    id: event.id,
    title: event.summary ?? "",
    description: event.description,
    location: event.location,
    status: event.transparency === "transparent" ? "free" : "busy",
  };
  if (event.start.date && event.end.date) {
    return {
      ...details,
      isAllDay: true,
      start: parseISO(event.start.date),
      // Google's end date is exclusive; the calendar's `end` is the last day
      end: subDays(parseISO(event.end.date), 1),
    };
  }

  return {
    ...details,
    start: new Date(event.start.dateTime ?? ""),
    end: new Date(event.end.dateTime ?? ""),
  };
}

function toGoogle(event: DetailedCalendarEvent) {
  const fields = {
    summary: event.title,
    description: event.description,
    location: event.location,
  };
  if (!event.isAllDay) {
    return {
      ...fields,
      start: { dateTime: event.start.toISOString() },
      end: { dateTime: event.end.toISOString() },
    };
  }

  return {
    ...fields,
    start: { date: format(event.start, "yyyy-MM-dd") },
    end: { date: format(addDays(event.end, 1), "yyyy-MM-dd") },
  };
}
```

### Load the visible range

Ask for the days on screen with `timeMin` and `timeMax`. `singleEvents=true` makes Google expand recurring events into occurrences, so a weekly meeting shows every week.

```ts
const GOOGLE_EVENTS_URL =
  "https://www.googleapis.com/calendar/v3/calendars/primary/events";

async function fetchGoogleEvents(accessToken: string, from: Date, to: Date) {
  const params = new URLSearchParams({
    timeMin: from.toISOString(),
    timeMax: to.toISOString(),
    singleEvents: "true",
    orderBy: "startTime",
    maxResults: "2500",
  });
  const response = await fetch(`${GOOGLE_EVENTS_URL}?${params}`, {
    headers: { Authorization: `Bearer ${accessToken}` },
  });
  if (!response.ok) throw new Error(`Google Calendar: ${response.status}`);

  const data: { items: GoogleEvent[] } = await response.json();
  return data.items.map(fromGoogle);
}
```

`visibleDays` from `useCalendar()` holds the days on screen. Fetch again whenever its first or last day changes:

```tsx
interface LoadVisibleRangeProps {
  accessToken: string;
  onLoad: (events: DetailedCalendarEvent[]) => void;
}

function LoadVisibleRange({ accessToken, onLoad }: LoadVisibleRangeProps) {
  const { visibleDays } = useCalendar();
  const firstDay = visibleDays[0]?.getTime();
  const lastDay = visibleDays[visibleDays.length - 1]?.getTime();

  React.useEffect(() => {
    if (firstDay === undefined || lastDay === undefined) return;
    let isCurrent = true;
    fetchGoogleEvents(
      accessToken,
      new Date(firstDay),
      addDays(new Date(lastDay), 1),
    ).then((events) => {
      // Skip responses for a range the user already navigated away from
      if (isCurrent) onLoad(events);
    });
    return () => {
      isCurrent = false;
    };
  }, [accessToken, firstDay, lastDay, onLoad]);

  return null;
}
```

### Write changes back

`onEventUpdate` fires after every drag, resize or edit in the details. Send the change to Google with a `PATCH`:

```tsx
async function saveToGoogle(accessToken: string, event: DetailedCalendarEvent) {
  await fetch(`${GOOGLE_EVENTS_URL}/${encodeURIComponent(event.id)}`, {
    method: "PATCH",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(toGoogle(event)),
  });
}

export function GoogleCalendar({ accessToken }: { accessToken: string }) {
  const [events, setEvents] = React.useState<DetailedCalendarEvent[]>([]);

  return (
    <CalendarProvider
      events={events}
      onEventsChange={setEvents}
      onEventUpdate={(event) => void saveToGoogle(accessToken, event)}
    >
      <LoadVisibleRange accessToken={accessToken} onLoad={setEvents} />
      <WeekView />
    </CalendarProvider>
  );
}
```

An occurrence of a recurring event has its own id (`eventId_20260601T130000Z`), so a `PATCH` to it changes only that occurrence. New events work the same way with `onEventCreate` and a `POST` to `GOOGLE_EVENTS_URL`: swap the local id for the one Google returns.

### Read-only: subscribe to an iCal address

Without an OAuth client, you can show a Google calendar read-only. In Google Calendar, open the calendar's settings and copy **Secret address in iCal format**. Google doesn't allow cross-origin requests to it, so fetch it from your server and parse it with `parseIcs()` on either side:

```ts title="app/api/calendar/route.ts"
export async function GET() {
  // Keep the secret address on the server: anyone with it can read the calendar
  const response = await fetch(process.env.GOOGLE_ICAL_URL ?? "", {
    next: { revalidate: 300 },
  });
  return new Response(await response.text(), {
    headers: { "Content-Type": "text/calendar; charset=utf-8" },
  });
}
```

The file holds each repeating event once, with its rule, and the views draw its dates, so this suits small calendars best.

## API Reference

### parseIcs

```ts
function parseIcs(text: string): DetailedCalendarEvent[];
```

Reads every `VEVENT` in the text, in file order, and turns a cancelled occurrence of a recurring event into an excluded date of its series, skips other cancelled events, events without a start, and other components. An event without a `UID` gets `ics-event-N`, and a repeated id gets `-2`, `-3`, ….

### toIcsCalendar

```ts
function toIcsCalendar<TEvent extends DetailedCalendarEvent>(
  fileName: string,
  events: TEvent[],
  calendars: CalendarInfo[],
): { calendar: CalendarInfo; events: TEvent[] };
```

Names the calendar after the file without `.ics` ("Imported calendar" when nothing is left) and gives it the id `ics:<name>`, so the same file returns the calendar already in `calendars`. A new one takes the first color none of `calendars` has. Each event gets the calendar's id as its `calendarId`; a `COLOR` of its own stays.

### toIcs

```ts
function toIcs(
  events: readonly DetailedCalendarEvent[],
  options?: ToIcsOptions,
): string;
```

| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `calendarName` | `string` | – | Calendar name, written as `X-WR-CALNAME`. Google Calendar and Apple Calendar show it. |
| `prodId` | `string` | `"-//CalendarCN//CalendarCN//EN"` | Product identifier, written as `PRODID`. |
| `timestamp` | `Date` | `new Date()` | Time the file is created, written as `DTSTAMP`. Pass a fixed date for output that doesn't change between runs. |
