Calendar
Calendars and events with RFC 5545 recurrence, per-occurrence edits, attendees, iCalendar import and export, and an iCal feed through a share link.
calendar stores calendars and their events in Postgres. A recurring event is
one row with an RFC 5545 RRULE; occurrences() expands it in TypeScript with
the same expandRule the reminders block uses, so
both agree on every date. Editing one occurrence writes an override row, and
editing "this and following" splits the series in two.
better-supabase add calendarThe block's entities are calendar_event (the calendar_events table, its primary entity) and calendar (the calendars table). Installing it registers calendar_event as a subject, searchable by title, description and location when the search module is installed. Rename them with blocks.calendar.names, for example { calendar_event: "meeting" }. calendarEventInputSchema validates what upsert takes.
import { createCalendar } from "better-supabase/blocks/calendar";The module requires memberships and access. With share-links it serves an
iCal feed, with reminders each event gets a recurrence rule that reminders
can attach to, with leave approved leave counts as out of office, and with
outbox its events are recorded.
Tables
| Table | Holds |
|---|---|
calendars | A named calendar in an organization, with an IANA tz and an optional owner subject (owner_type, owner_id) |
calendar_events | starts_at, ends_at (exclusive), all_day, tz, status, rrule, exdates, an optional subject, and override columns |
calendar_attendees | An email per event, with an optional user id, a role and a response |
calendar_event_alarms | An event's alarms: a method, an offset_minutes offset or a trigger_at time, a repeat count, and an optional user_id |
calendar_working_hours | A member's weekly hours in an organization: a weekday with a starts_at and ends_at time in their tz |
An override has recurrence_id (the series row) and original_starts_at (the
occurrence it replaces) and shares the series' uid, as RECURRENCE-ID does
in iCalendar. Members read through the tables' policies; every write goes
through a function that checks calendar.write, or calendar.manage to
create and delete calendars. Deleting a user keeps the events they created.
Events and occurrences
Server code calls the calendar instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useCalendar } = defineDataHooks(
"calendar",
(db: AppDb) => db.calendar,
);const { id: calendarId } = await db.calendar
.createCalendar(organizationId, "Team", { tz: "Europe/Amsterdam" })
.orThrow();
await db.calendar
.upsert(calendarId, {
title: "Stand-up",
startsAt: Temporal.Instant.from("2026-03-23T08:00:00Z"),
endsAt: Temporal.Instant.from("2026-03-23T08:15:00Z"),
tz: "Europe/Amsterdam",
rrule: "FREQ=WEEKLY;BYDAY=MO",
})
.orThrow();
const week = await db.calendar
.occurrences([calendarId], {
from: Temporal.Instant.from("2026-03-30T00:00:00Z"),
until: Temporal.Instant.from("2026-04-06T00:00:00Z"),
})
.orThrow();"use client";
import { useCalendar } from "@/lib/supabase/hooks";
const rows = useCalendar({ limit: 50 });A series follows its tz: the stand-up stays at 09:00 in Amsterdam across
the daylight saving change, so its UTC time moves. Each occurrence has a
stable key (the series id and its original start), its start and end,
and the event row that applies, which is the override when there is one.
| Method | Does |
|---|---|
upsert(calendarId, input) | Inserts an event, or updates the one with input.id; keys left out keep their value |
events(calendarIds, range) | The rows that can fall in the range: single events, series and overrides |
occurrences(calendarIds, range) | The occurrences in the range, with EXDATEs removed and overrides applied |
editOccurrence(occurrence, changes) | Changes one occurrence: an override for a series, an update for a single event |
editFollowing(occurrence, changes) | Changes this occurrence and every later one, splitting the series unless it is the first |
cancelOccurrence(occurrence) | Adds an EXDATE and drops the occurrence's override, or purges a single event. Also takes { seriesId, originalStart } |
purge(eventId) | Removes an event for good, with its overrides. Set status to cancelled to keep it |
setAttendee, removeAttendee | Invites or removes an attendee by email |
respond(eventId, response) | The signed-in user answers: accepted, declined, tentative or needs-action |
A new event's created_by (and its owner_id with per-calendar access) is
the signed-in user. A server that saves on a member's behalf, such as a sync
job running as the service role, passes the member as
upsert(calendarId, input, { actor: userId }). Only the service role may
name a user other than the caller (CALENDAR_FORBIDDEN).
editFollowing ends the old series the second before the occurrence (its
COUNT becomes an UNTIL) and starts a new series there with the remaining
count and a new uid. EXDATEs and overrides after the split move to the new
series. splitRule(rrule, dtstart, at) computes both rules if you need them
yourself.
Read a page in one call
A calendar page needs the calendars, the events of the visible month, the next
events and the reminders on them. bootstrap reads all of it in one database
call, where listCalendars, occurrences and one reminders read per event make
several:
const now = Temporal.Now.instant();
const page = await db.calendar
.bootstrap({
organizationId,
range: { from: monthStart, until: monthEnd },
upcoming: { from: now, until: now.add({ hours: 14 * 24 }) },
})
.orThrow();
// page.calendars, page.occurrences, page.upcoming and page.remindersoccurrences and upcoming are expanded the way occurrences() expands them.
reminders holds the caller's reminders on events ({ id, eventId, offsetMinutes }), and is empty without the reminders block or without the
right to manage reminders. upcoming is optional. The SQL function
calendar_bootstrap(tenant, range_start, range_end, upcoming_start, upcoming_end) runs as the caller, so the policies decide what each part holds.
Run better-supabase upgrade to write it into an installed block.
No overlapping events
noOverlap: true adds the calendar_events_no_overlap_excl exclusion constraint
(btree_gist). Two timed, opaque, non-recurring, non-cancelled events on the
same calendar can't cover the same time range. It is off by default because
existing data may already overlap.
Availability
Each member can set weekly working hours, mark time as out of office or focus
time, and anyone in the organization with calendar.read can ask when a set of
members is busy. Postgres computes the answer, so a series' recurrence, an
override and an approved leave request all count without the client loading
every event.
import { commonFreeTime } from "better-supabase/blocks/calendar";
await calendar
.setWorkingHours(organizationId, {
tz: "Europe/Amsterdam",
hours: [
{ weekday: 1, start: "09:00", end: "17:00" },
{ weekday: 3, start: "13:00", end: "17:00" },
],
})
.orThrow();
await calendar
.upsert(calendarId, {
title: "Deep work",
kind: "focus_time",
autoDecline: true,
startsAt: Temporal.Instant.from("2030-03-06T08:00:00Z"),
endsAt: Temporal.Instant.from("2030-03-06T10:00:00Z"),
})
.orThrow();
const day = {
from: Temporal.Instant.from("2030-03-06T00:00:00Z"),
until: Temporal.Instant.from("2030-03-07T00:00:00Z"),
};
const freeBusy = await calendar
.freeBusy(organizationId, [ada, bob], day)
.orThrow();
const free = commonFreeTime(freeBusy, day, {
minimum: Temporal.Duration.from({ minutes: 30 }),
});An event's kind is event, out_of_office or focus_time, and its
transparency is opaque or transparent (the iCalendar TRANSP property,
which importIcs and exportIcs map). A member is busy during:
- events on calendars they own (
owner_typeuser), except transparent and cancelled ones; - events they are invited to and haven't declined;
- approved leave, when the leave block is installed: a full day, or the morning or afternoon half, in their working-hours zone.
freeBusy returns, per member, the merged busy ranges, the
outOfOffice and focusTime ranges on their own, and their workingHours
for the range when they set some. Ranges are clipped to the range you ask
for; one call covers at most 62 days and 100 members. commonFreeTime is a
pure function over that answer: it removes everyone's busy time and keeps the
time inside everyone's working hours (pass workingHours: false to skip that).
Recurring events expand in SQL with calendar_rule_starts, a PL/pgSQL port of
expandRule; an integration test runs both over the same rules, including
daylight saving changes, and expects the same instants.
Auto-decline
An out-of-office block always declines new invitations that it covers. A
focus time block declines them when autoDecline is set. The decline happens
when the invitation is written, and when a block is saved it declines the
open invitations it already covers. Approved leave counts as out of office.
A recurring block, and an invitation to a recurring event, is never declined
automatically; the member answers those.
| Method | Does |
|---|---|
setWorkingHours(organizationId, input) | Replaces a member's hours; managers pass userId to set someone else's |
workingHours(organizationId, userIds?) | The hours of the members that set them |
freeBusy(organizationId, userIds, range) | Busy, out-of-office, focus and working-hours ranges per member |
To offer an appointment schedule (a link where others book time with a member), use the bookings block with the member as a resource's host: its slots then skip the times this section reports as busy.
iCalendar
importIcs parses an RFC 5545 file and upserts its events by UID, and
RECURRENCE-ID events become overrides of their series. Importing the same
file again updates the events instead of duplicating them. exportIcs writes
the calendar back, with a VTIMEZONE for every zone its events use.
const summary = await calendar.importIcs(calendarId, text).orThrow();
// { created: 12, updated: 0, skipped: 1 }
const ics = await calendar
.exportIcs({ id: calendarId, name: "Team", tz: "Europe/Amsterdam" })
.orThrow();The parser and writer are in the package (parseIcs, toIcs): they unfold
and fold lines at 75 octets, escape TEXT, and read TZID, UTC, floating and
all-day times, DURATION, EXDATE, STATUS, TRANSP, ATTENDEE and
VALARM. VTODO is skipped.
Alarms
An event's alarms are VALARM components: data on the event that every
reader gets, fired by the reader's own calendar client. exportIcs and the
feeds write them, and importIcs reads them. A reminder that your server
sends to one member is a reminder instead.
await calendar
.upsert(calendarId, {
title: "Review",
startsAt: Temporal.Instant.from("2030-03-06T09:00:00Z"),
endsAt: Temporal.Instant.from("2030-03-06T10:00:00Z"),
alarms: [
{ method: "display", offsetMinutes: 15 },
{
method: "email",
offsetMinutes: 0,
at: Temporal.Instant.from("2030-03-05T18:00:00Z"),
summary: "Prepare the review",
repeat: 2,
repeatMinutes: 5,
},
],
})
.orThrow();An alarm has the same shape as a feed reminder (CalendarReminder), with a
method of display, email or audio. offsetMinutes counts back from
the event's start, or from its end with related: "end", so 15 fires a
quarter of an hour before and a negative number fires after; at is an
absolute time and replaces the offset. repeat fires it again that many
times, repeatMinutes apart. Passing alarms replaces the event's alarms,
and leaving it out keeps them. An event holds at most 20, and
calendarAlarmSchema validates one. An override is its own row with its own
alarms. On import, the seconds of a trigger are dropped, since alarms count in
whole minutes.
The alarms live in tables.alarms (calendar_event_alarms). Set it to
null to leave alarms out, or map it to a table your app already has, with
its columns under columns.alarms:
calendar: {
tables: { alarms: "public.event_alarms" },
columns: {
alarms: {
offsetMinutes: "minutes_before",
method: "action",
user: "user_id",
related: null,
at: null,
repeat: null,
repeatMinutes: null,
description: null,
summary: null,
createdAt: null,
},
},
},The table needs tenant and event columns and an offset; user,
method, related, at, repeat, repeatMinutes, description,
summary and createdAt can each be null when your table lacks them. A
row with a user is that member's own alarm: only they read it, and saving the
event's alarms leaves it alone.
Default alarms
With options.defaultAlarms: true, each calendar keeps the alarms a new event
gets when its input sets no alarms, in calendar_default_alarms. A default
counts for timed events, or with allDay for all-day ones. An all-day
default counts its offsetMinutes back from anchor (HH:MM, default
09:00) on the event's day, so { allDay: true, offsetMinutes: 1440 } alarms
at 09:00 the day before. The event stores the result as an ordinary alarm, so
changing the defaults later leaves saved events alone, and an input with
alarms: [] saves an event without any.
await db.calendar
.setDefaultAlarms(calendarId, [
{ offsetMinutes: 10 },
{ allDay: true, offsetMinutes: 1440, anchor: "08:30" },
])
.orThrow();
const defaults = await db.calendar.defaultAlarms(calendarId).orThrow();setDefaultAlarms replaces the calendar's defaults and needs the right to
manage the calendar; members who read the calendar read them. Overrides of a
recurring event don't get defaults. The option needs the alarms table, and
over your own tables you map tables.defaultAlarms with tenant,
calendar, allDay and offsetMinutes columns; method, anchor and
createdAt can be null.
iCal feed
With share-links installed, a share link to a calendar (subjectType: "calendar") works as a subscription URL. calendar_feed(token) is open to
anon, hashes the token before the lookup and returns nothing for a revoked,
expired or unknown token, or a link whose organization is not the calendar's.
const link = await shareLinks
.create(organizationId, "calendar", calendarId, "view")
.orThrow();export async function GET(
_request: Request,
{ params }: { params: Promise<{ token: string }> },
) {
const { token } = await params;
const ics = await calendar.feed(token).orThrow();
if (ics === null) return new Response("Not found", { status: 404 });
return new Response(ics, {
headers: { "content-type": "text/calendar; charset=utf-8" },
});
}The feed carries the link's creator as createdBy, and each event's
reminders become VALARMs: the event's alarms (with the creator's own
alarm rows) and, with the reminders block
installed, the creator's reminders for the event. A reminder whose method is
not an iCalendar action, such as notification, is written as a display
alarm with an X-BSB-METHOD property, and importIcs skips it.
feedData(token) returns what feed serializes, parsed, for an app that
writes the iCalendar itself: the calendar with its color, the
organization (id and name, with the organizations block), createdBy,
and the events with their reminders, attendees and extra columns.
userFeedData(token) does the same for a user feed. toIcs stays available
for the events.
const data = await calendar.feedData(token).orThrow();
if (data === null) return new Response("Not found", { status: 404 });
const ics = toIcs(data.events, {
name: data.calendar.name,
tz: data.calendar.tz,
});Event keys and read-only events
Three event actions take their own key when you set one, on top of
calendar.write: permissions.create gates new events and overrides,
permissions.update gates changes to an event, permissions.purge gates
purging an event (it falls back to permissions.delete when unset), and
permissions.delete gates cancelling an occurrence. Importing goes through the same
checks. options.readOnly names a column of the events table and the values
that lock an event, such as events a sync owns. A locked event can't be
changed, purged, cancelled or split, and no override can be added to it,
except by the service role (CALENDAR_EVENT_READ_ONLY):
calendar: {
permissions: { create: "agenda.create", delete: "agenda.delete" },
options: { readOnly: { column: "source", values: ["google", "microsoft"] } },
}Per-calendar access
By default every member with calendar.read reads every calendar of the
organization, and calendar.write changes any of them. options.access makes
access per calendar:
- Calendars get a
visibility(sharedorprivate) and useowner_typeandowner_idas their owner. A calendar withoutowner_typebelongs to the user inowner_id. - Events get a
visibility(publicorprivate) and anowner_id, set to the caller on insert. - The owner of a calendar reads, writes and manages it. An
editorgrant writes it and sees its private events, aviewergrant reads it. On a shared calendarcalendar.read,calendar.writeandcalendar.managedecide as before; on a private one they don't. - A private event shows only to its owner, the calendar's owner and its editors. Free/busy still counts it as busy, without a title.
Every write function checks the calendar or event it changes, the read
policies of the calendars, events and attendees tables call
calendar_access(calendar_id, user_id, action) and
calendar_event_access(event_id, user_id, action), and a feed link serves a
private calendar only while the member who made it can still read it. Both
functions answer for the caller only and return false for another user_id,
unless the service role asks. The feeds check the link's creator through
calendar_access_for and calendar_event_access_for, which no client role
can execute. Members
create calendars they own with calendar.write; other calendars need
calendar.manage.
const { id } = await calendar
.createCalendar(organizationId, "Personal", {
ownerType: "user",
ownerId: userId,
visibility: "private",
})
.orThrow();
await calendar.setGrant(id, assistantId, "editor").orThrow();
await calendar.upsert(id, {
title: "Dentist",
visibility: "private",
startsAt,
endsAt,
});Grants live in tables.grants (calendar_grants, or your table once mapped)
with columns.grants.role holding viewer or editor. When your app already
decides calendar access, name your functions in options.accessFunctions:
each takes (calendar_id uuid, user_id uuid), returns a boolean, and replaces
the built-in rule for reading (read) or for writing, managing and seeing
private events (write), and share for making a share link (write when
unset). The caller still needs calendar.read.
When an authorization provider
grants access per calendar, name its resource and a permission key instead of a
function, and the block generates the check (blocks.permissions.model: "provider" and the provider's rowsWith template):
calendar: {
options: {
access: true,
accessFunctions: {
read: { rows: "team_calendar", key: "teamCalendar.read" },
write: { rows: "team_calendar", key: "teamCalendar.update" },
},
},
},The signed-in caller is checked through rowsWith, with their own claims.
A feed checks the link's creator, who is not signed in, through the provider's
rowsWithFor; without it a feed serves no calendar that only a row grant
opens. When the creator loses the grant, or the provider disables them, the
feed returns nothing on the next fetch.
Feed per member
With share-links and options.userFeed, a share link whose subject is a user
(subjectType: "calendar_user") serves every calendar that user can read as
one feed. Only the user can make the link. calendar_user_feed(token) is open
to anon like calendar_feed, and userFeed(token) returns the iCalendar
text.
const link = await shareLinks
.create(organizationId, "calendar_user", userId, "view")
.orThrow();
const ics = await calendar.userFeed(link.token).orThrow();Recurrence storage
options.rdates adds an rdates timestamptz[] column: extra occurrence starts
next to the RRULE, which occurrences(), free/busy, exportIcs (RDATE) and
importIcs honour. An EXDATE removes an RDATE as it removes a rule's
occurrence.
options.recurrence: "table" keeps rules and dates out of the event row, for
an app that stores them in their own tables:
tables.rulesholds one row per series:columns.rules.eventand eithercolumns.rules.rrule(theRRULEtext) or structured columnscolumns.rules.freq,interval,count,until,byDay,byMonthDay,byMonthandbySetPos, each mapped or set tonull. The list columns are arrays (text[]forbyDay,integer[]for the others).tables.recurrenceDatesholds one row per date:columns.recurrenceDates.event,columns.recurrenceDates.kind(rdateorexdate) andcolumns.recurrenceDates.at.
columns.events.rrule and columns.events.exdates can then be null. Saving,
cancelling an occurrence, splitting a series, importing and every read go
through those tables. values.rules.freq and values.recurrenceDates.kind
map the labels to your enums. A rules table keyed by its event maps
columns.rules.id to null.
options.ruleDialect reads and writes the structured columns in your own
shape, over your own rules table with columns.rules.rrule: null:
ruleDialect: {
weekdays: "lower", // byDay holds mo, tu, ... instead of MO, TU, ...
monthDay: "scalar", // byMonthDay is one integer, not a list
ordinal: { weekday: "month_weekday", position: "month_ordinal" },
},With ordinal, a rule such as BYDAY=2TU goes into the two named columns
and leaves byDay empty; reads turn them back into BYDAY=2TU.
Attendees without an email
options.attendeeKey: "any" finds an attendee by user, email or subject record:
columns.attendees.email and columns.attendees.role may be null, and
columns.attendees.subjectType, subjectId, organizer and optional add a
record attendee and its flags. set_calendar_attendee(event_id, attendee)
updates the matching row or inserts one, so your table needs no unique
constraint, and returns its id; delete_calendar_attendee(attendee_id)
removes one. The old signatures keep working.
await calendar
.setAttendee(eventId, { subjectType: "contact", subjectId, optional: true })
.orThrow();
await calendar.removeAttendeeById(attendeeId).orThrow();Calendar details
options.calendarDetails adds description, rank and is_default to the
calendars table. createCalendar takes them, listCalendars returns them
ordered by rank, and updateCalendar(id, attributes) changes the name, time
zone, color, details and, with options.access, the visibility. Setting
isDefault clears it on the owner's other calendars. calendar.updated is
recorded.
An owner column of another type, such as a uuid, takes
values.calendars.ownerId: {}, which casts the owner to its type. The event
kind and transparency and the attendee role and response may be enum
columns too: the block casts its labels to the column's type, and a
values map renames them when your labels differ.
Over your own tables
blocks: {
calendar: {
tables: {
calendars: "public.calendars",
events: "public.events",
attendees: "public.attendees",
grants: "public.calendar_shares",
rules: "public.event_rules",
recurrenceDates: "public.event_dates",
workingHours: null,
},
columns: {
calendars: { tenant: "organization_id", ownerType: null, ownerId: "owner_id", rank: "position" },
events: { tenant: "organization_id", rrule: null, exdates: null, rdates: null, owner: "owner_id" },
attendees: { tenant: "organization_id", role: null, subjectType: "record_type", subjectId: "record_id" },
grants: { tenant: "organization_id", role: "access" },
rules: { rrule: null, freq: "frequency", interval: "every", count: "occurrences", until: "ends_at", byDay: "weekdays", byMonthDay: "month_days", byMonth: null, bySetPos: null },
recurrenceDates: { at: "occurs_at" },
},
values: {
calendars: { visibility: { shared: "team", private: "personal" }, ownerId: {} },
events: { visibility: { public: "normal", private: "secret" } },
rules: { freq: { DAILY: "daily", WEEKLY: "weekly", MONTHLY: "monthly", YEARLY: "yearly" } },
recurrenceDates: { kind: { rdate: "extra", exdate: "skip" } },
},
options: {
access: true,
userFeed: true,
recurrence: "table",
attendeeKey: "any",
calendarDetails: true,
},
},
},React
useCalendar loads the occurrences of a visible range and returns them in the
shape an event calendar renders. The hook is a registry item: install it with
npx shadcn add @better-supabase/use-calendar, which writes
hooks/use-calendar.ts into the app. The hook is typed structurally, so it
needs no UI library.
"use client";
import { useCalendar } from "@/hooks/use-calendar";
const { events, loading, editOccurrence, editFollowing, cancelOccurrence } =
useCalendar({ calendarIds, range: { start, end } });Each event's id is the occurrence key and its data is the occurrence, so
a drop or a resize maps back with fromEventCalendarUpdate.
toEventCalendarResources turns calendars into resources for a resource view;
by default each event's resource is its calendar, and resourceOf picks
another one, such as the event's subject.
Vue
useBlockController from better-supabase/vue runs createCalendarController
with its options, as
Block controllers explains.
state is a shallow ref of the snapshot and actions are the controller's
actions. The work starts on mount, and the controller is disposed with the
component.
<script setup lang="ts">
import { useBlockController, useSupabase } from "better-supabase/vue";
import {
createCalendar,
createCalendarController,
} from "better-supabase/blocks/calendar";
import { rpcTransport } from "better-supabase/blocks";
const { calendarId } = defineProps<{ calendarId: string }>();
const supabase = useSupabase();
const { state } = useBlockController(
createCalendarController,
{
client: createCalendar({ transport: rpcTransport(supabase) }),
calendarIds: [calendarId],
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
},
false,
);
</script>
<template>
<ul>
<li v-for="occurrence in state.occurrences ?? []" :key="occurrence.key">
{{ String(occurrence.start) }}
</li>
</ul>
</template>Call actions.setRange(range) when the visible range changes.
Svelte
useBlockController from better-supabase/svelte runs
createCalendarController with its options. It returns a readable store of the
snapshot, read with $, with the actions on .actions. The work starts on
mount, and the controller is disposed with the component.
<script lang="ts">
import {
betterSupabase,
useBlockController,
} from "better-supabase/svelte";
import {
createCalendar,
createCalendarController,
} from "better-supabase/blocks/calendar";
import { rpcTransport } from "better-supabase/blocks";
let { calendarId }: { calendarId: string } = $props();
const { supabase } = betterSupabase();
const calendar = useBlockController(createCalendarController, {
client: createCalendar({ transport: rpcTransport(supabase) }),
calendarIds: [calendarId],
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
}, false);
</script>
<ul>
{#each $calendar.occurrences ?? [] as occurrence (occurrence.key)}
<li>{String(occurrence.start)}</li>
{/each}
</ul>Solid
useBlockController from better-supabase/solid runs
createCalendarController with its options. state() reads the snapshot
through from, and actions are the controller's actions. The work starts on
mount, and the controller is disposed with the owner.
import { For } from "solid-js";
import { useBlockController, useSupabase } from "better-supabase/solid";
import {
createCalendar,
createCalendarController,
} from "better-supabase/blocks/calendar";
import { rpcTransport } from "better-supabase/blocks";
export function Component(props: { calendarId: string }) {
const supabase = useSupabase();
const { state } = useBlockController(
createCalendarController,
{
client: createCalendar({ transport: rpcTransport(supabase) }),
calendarIds: [props.calendarId],
range: { start: new Date(), end: new Date(Date.now() + 7 * 86_400_000) },
},
false,
);
return (
<ul>
<For each={state().occurrences ?? []}>
{(occurrence) => <li>{String(occurrence.start)}</li>}
</For>
</ul>
);
}Public holiday calendars
seed_calendar_defaults creates a "Public holidays" calendar with one all-day event per holiday, chosen by the locale you pass to seed_tenant_defaults:
| Locale | Calendar | Holidays |
|---|---|---|
nl | Public holidays (NL) | Dutch national days, King's Day moved off a Sunday |
de | Public holidays (DE) | Days every German state observes |
fr | Public holidays (FR) | The eleven jours fériés |
en-gb | Public holidays (GB) | Bank holidays of England and Wales, with substitute days |
en-us | Public holidays (US) | Federal holidays on their actual dates, without observed days |
Other locales, including en, get no calendar. The events cover the fixed years 2026 to 2030, so the rows are the same on every run. Each event has a stable uid such as holiday-nl-2026-04-27, starts at midnight in the calendar's time zone and ends at the next midnight. Running the defaults again keeps existing events, and a release that adds years adds only the new events.
Hooks
before_calendar_event_save(tenant, calendar, item) runs before an insert or
update and can raise to refuse it; after_calendar_event_save(event) runs
after it. See block hooks.
Errors
| Hint | When |
|---|---|
CALENDAR_FORBIDDEN | The caller lacks calendar.write, calendar.manage or the create, update or delete key |
CALENDAR_EVENT_READ_ONLY | The event matches options.readOnly |
CALENDAR_NOT_FOUND | The calendar does not exist |
CALENDAR_EVENT_NOT_FOUND | The event does not exist in that calendar |
CALENDAR_EVENT_INVALID | A missing start or end, an end before the start, a bad status, or an override without a series |
CALENDAR_TZ_INVALID | tz is not an IANA time zone |
CALENDAR_HOURS_INVALID | Working hours that aren't { weekday 1-7, start HH:MM, end HH:MM } with the end after the start |
CALENDAR_RANGE_INVALID | A free/busy range longer than 62 days, or no members or more than 100 |
CALENDAR_SPLIT_INVALID | The split is at or before the series' first occurrence |
CALENDAR_ATTENDEE_NOT_FOUND | The caller is not invited to the event, or the attendee id is unknown |
CALENDAR_RESPONSE_INVALID | The response is not one of the four values |
CALENDAR_INVALID | A visibility that isn't shared or private, or a private calendar without an owner |
CALENDAR_GRANT_INVALID | A grant without a user, or a role that isn't viewer or editor |
CALENDAR_ATTENDEE_INVALID | An attendee without a user id, an email or a subject |
With ReUI
ReUI's Event Calendar renders useCalendar's events directly: month, week,
day and agenda views, drag to move and resize, and resource views from
toEventCalendarResources. Install it with
npx shadcn@latest add @reui/event-calendar; the free examples
c-event-calendar-1 to c-event-calendar-5 show each view. The Pro blocks
in the application/event-calendar category build full scheduling screens on
it; their source is licensed per user, so copy them into your app from
reui.io.
Your own fields
Columns you add to calendar_events with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createCalendar a Standard Schema
for them as fields: upsert and the occurrence edits take them next to the block's own keys and
validate them (a bad value is a validation error), and events return them
parsed. A column the module already uses is refused. See
your own fields.
A column you add to the calendars table does the same: createCalendar(organizationId, name, { fields }) writes
them (one that is not null without a default inside the insert), and
listCalendars returns them under fields.
const client = createCalendar({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.calendar is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
const calendar = createCalendar({ transport });
const { id: calendarId } = await calendar
.createCalendar(organizationId, "Team", { tz: "Europe/Amsterdam" })
.orThrow();
await calendar
.upsert(calendarId, {
title: "Stand-up",
startsAt: Temporal.Instant.from("2026-03-23T08:00:00Z"),
endsAt: Temporal.Instant.from("2026-03-23T08:15:00Z"),
tz: "Europe/Amsterdam",
rrule: "FREQ=WEEKLY;BYDAY=MO",
})
.orThrow();
const week = await calendar
.occurrences([calendarId], {
from: Temporal.Instant.from("2026-03-30T00:00:00Z"),
until: Temporal.Instant.from("2026-04-06T00:00:00Z"),
})
.orThrow();Paging events and calendars
page pages the stored events the caller can read, and pageCalendars({ organizationId }) pages the calendars. The event page returns the stored rows: a series and its overrides stay unexpanded, so use events and occurrences when you need each occurrence. Event sorts are startsAt, title and updatedAt. Event filters are calendarId, status, subjectType, subjectId, from and to (an instant), facets are status and calendarId, and q searches the title and the location. Calendars sort by name, filter and facet by ownerType, and q searches the name. facets, count and getEvent serve events; calendarFacets, countCalendars and getCalendar serve calendars. Both gets return a not_found error for a missing row. listCalendars is deprecated.
const page = await calendar
.page({
filters: { calendarId: [calendarId], from: ["2027-01-01T00:00:00Z"] },
})
.orThrow();Last updated on
Reminders
RFC 5545 recurrence and reminders, expanded in TypeScript and delivered through notifications.
Bookings
Bookable resources with weekly hours, services with buffers, open slots computed in SQL, holds that expire, double bookings refused by an exclusion constraint, and public booking through a share link.