# Architecture
URL: /core/architecture
## Edge-First Infrastructure [#edge-first-infrastructure]
Recal runs on the edge for low-latency global performance.
**API** → [Cloudflare Workers](https://developers.cloudflare.com/workers/) (edge compute)
**Web/Dashboard** → [Vercel](https://vercel.com/) (edge functions)
Requests process close to users—no central bottleneck.
## Tech Stack [#tech-stack]
### Backend [#backend]
* **Hono** — TypeScript API framework
### Frontend [#frontend]
* **Next.js 15** — React framework with App Router
* **Fumadocs** — Documentation system (these docs)
* **Tailwind CSS** — Styling
## Resources [#resources]
* [Turborepo](https://turbo.build/docs)
* [Hono](https://hono.dev/)
* [Next.js](https://nextjs.org/docs)
* [Cloudflare Workers](https://developers.cloudflare.com/workers/)
# Dashboard
URL: /core/dashboard
The Dashboard at [dash.recal.dev](https://dash.recal.dev) is your control panel for managing integrations and users.
## Sections [#sections]
**Usage Dashboard** — Metrics, activity, API request volumes
**API Keys** — Create tokens for authentication (copy immediately—shown once)
**Organizations** — Create and manage customer workspaces
**Users** — Add users, assign to organizations, monitor calendar connections
**Settings** — Configure OAuth credentials for Google/Outlook
## Quick Tasks [#quick-tasks]
### Create an API Key [#create-an-api-key]
API Keys → Create New Key → Copy token
### Add an Organization [#add-an-organization]
Organizations → Create → Set custom slug for your database mapping
### Create a User [#create-a-user]
Users → Add User → Assign to organizations (optional)
### Configure OAuth [#configure-oauth]
Settings → OAuth Credentials → Add Google/Outlook credentials
See setup guides: [Google](/core/oauth/google) | [Microsoft](/core/oauth/microsoft)
## Best Practices [#best-practices]
**Separate Keys** — Use different API keys for dev/staging/production
**Monitor Usage** — Check dashboard regularly to track costs
**Secure Credentials** — Never commit OAuth secrets to version control
## Troubleshooting [#troubleshooting]
**Connection Errors** → Verify OAuth credentials in Settings
**Permission Issues** → Check API key scopes
Need help? Email [team@recal.dev](mailto:team@recal.dev)
## Next Steps [#next-steps]
# Core Concepts
URL: /core/entities
## The Basics [#the-basics]
**Organizations** — Group users together (optional for B2C, essential for B2B)
**Users** — Connect to calendar providers (Google, Outlook). Support custom IDs.
**Events** — Calendar entries synced across providers
**OAuth Connections** — Secure calendar provider authentication tokens
## Data Model [#data-model]
Recal's data model is built around four core entities that work together:
* **Users** connect to calendar providers and can belong to multiple organizations
* **Organizations** group users together for B2B multi-tenancy
* **Events** are calendar entries synced across all providers in a unified format
* **OAuth Connections** securely link users to their Google/Microsoft calendars
For detailed TypeScript type definitions, see the [SDK Types Reference](/sdk/types).
## Architecture Patterns [#architecture-patterns]
### B2B Multi-Tenant [#b2b-multi-tenant]
Create **organizations** for each customer. Isolates data and enables per-tenant analytics.
**Example:** Salon booking platform
### B2C Direct Users [#b2c-direct-users]
Add users directly without **organizations**. Simpler for consumer apps.
**Example:** Personal calendar app
## When to Use What [#when-to-use-what]
| Pattern | Use Case | Benefits |
| ----------------- | ------------------------- | ---------------------------------------- |
| **Organizations** | B2B SaaS, team scheduling | Data isolation, per-tenant analytics |
| **Direct Users** | B2C apps, personal tools | Simpler setup, faster onboarding |
| **Hybrid** | Both patterns combined | Flexibility for different customer types |
## Key Features [#key-features]
**Custom IDs** — Map to your database IDs directly (e.g., `${yourDbId}` or `user_clerk-id`)
**Multi-Org Users** — One person can belong to multiple organizations
**Cross-Calendar Sync** — Events stay in sync across Google, Outlook, etc.
**Shared Availability** — Find free slots across organization members
## Next Steps [#next-steps]
# Introduction
URL: /core
# Build Calendar Integrations with Recal [#build-calendar-integrations-with-recal]
Recal is a developer platform for building calendar integrations. One API connects to Google Calendar, Microsoft Outlook, and more—no provider-specific code required.
If you have questions, reach out at [team@recal.dev](mailto:team@recal.dev).
## How It Works [#how-it-works]
Recal sits between your application and calendar providers:
* **OAuth Integration** → Users connect their calendars through standard flows
* **Unified API** → Your code stays consistent across all providers
## What You Can Build [#what-you-can-build]
* **Scheduling Tools** — Find availability across teams and calendars
* **Event Management** — Create, update, and delete calendar events
* **AI Integrations** — Build agents that manage meetings automatically
* **Custom Workflows** — Sync calendar data with your existing systems
All without building provider-specific integrations.
## Getting Started [#getting-started]
## AI & LLM Access [#ai--llm-access]
These docs are optimized for AI assistants:
| Format | URL | Use |
| --------- | ---------------------------------- | --------------------- |
| Markdown | Any page + `.mdx` | Single page as MDX |
| Full text | [`/llms-full.txt`](/llms-full.txt) | All docs concatenated |
# Google Setup
URL: /core/oauth/google
Jump to [Enable the Calendar API](#2-enable-the-google-calendar-api), [Configure Consent Screen](#3-configure-oauth-consent-screen), or [Add to Recal](#6-add-to-recal).
### 1. Create Google Cloud Project [#1-create-google-cloud-project]
Go to [Google Cloud Console](https://console.cloud.google.com/) → Project selector → **New Project**.
### 2. Enable the Google Calendar API [#2-enable-the-google-calendar-api]
Search **"Google Calendar API"** → Click **Enable**.
### 3. Configure OAuth Consent Screen [#3-configure-oauth-consent-screen]
**APIs & Services** → **OAuth consent screen**:
* **User Type**: "External" (SaaS) or "Internal" (org-only)
* Fill required fields: app name, support email, developer email
* Click through remaining steps
**Testing mode**: Tokens expire in \~7 days. **Production mode**: No fixed expiry. Move to Production before launch. [Slack us](https://recal.dev/slack) for help.
An expired testing-mode token reports as `authorizationInvalid` — see [Troubleshooting](/core/troubleshooting#reconnect-a-calendar).
### 4. Understanding Scopes in Recal [#4-understanding-scopes-in-recal]
Recal simplifies OAuth scope management by offering easy-to-understand scope options that automatically map to the appropriate Google Calendar permissions:
#### Available Scopes [#available-scopes]
**`write` scope** - Read/write access to events (deprecated `edit` is still accepted)
* `https://www.googleapis.com/auth/userinfo.email` - User's email address
* `https://www.googleapis.com/auth/calendar.events` - Read/write access to events
* `https://www.googleapis.com/auth/calendar.readonly` - Read-only access to calendar list (no calendar modifications)
**`read` scope** - Read-only access to calendars and events
* `https://www.googleapis.com/auth/userinfo.email` - User's email address
* `https://www.googleapis.com/auth/calendar.readonly` - Read-only calendar and event access
**`free-busy` scope** - Read-only access to availability
* `https://www.googleapis.com/auth/userinfo.email` - User's email address
* `https://www.googleapis.com/auth/calendar.freebusy` - Busy time information only
Request minimum scopes needed. Insufficient access returns `403` with required permissions — re-authenticate with higher scope.
### 5. Create OAuth Credentials [#5-create-oauth-credentials]
**APIs & Services** → **Credentials** → **+ Create Credentials** → **OAuth client ID**:
* Application type: **Web application**
* **Authorized JavaScript origins**: `https://yourapp.com`
* **Authorized redirect URIs**: `https://yourapp.com/oauth2callback`
* Click **Create** and copy **Client ID** + **Client Secret**
### 6. Add to Recal [#6-add-to-recal]
In Recal dashboard → **OAuth Credentials** → Add Client ID, Client Secret, and redirect URL.
Redirect URL in Recal must exactly match the URI in Google Cloud Console.
# Overview
URL: /core/oauth
Connect your OAuth app so Recal can access users' calendars. Pick your provider:
Prefer to be walked through the console? Paste the [coding agent setup prompt](/core/oauth/setup-prompt) into your
agent and it will take you step by step, with Recal's requirements already filled in.
***
## Reference [#reference]
### Scopes [#scopes]
| Scope | Access |
| ----------- | --------------------------------------------------------------- |
| `write` | Read/write calendars and events, and availability |
| `read` | Read-only calendars and events, and availability |
| `free-busy` | Availability only — on Microsoft this grants the same as `read` |
| `edit` | **Deprecated** — synonym for `write`, to be removed |
The levels are a hierarchy: `write` covers everything `read` does, and `read` covers availability,
so a connection made with a higher level never needs a second one to read free/busy. Pick the
lowest level that covers what you need.
`free-busy` is the narrowest level each provider offers, which is not the same narrowness on both:
on Google it grants `calendar.freebusy`, which exposes busy intervals and nothing else, while
Microsoft Graph has no free/busy-only permission, so it grants `Calendars.Read` — the same as
`read`. If a connection must not expose event titles or attendees, that is achievable on Google
and not on Microsoft.
Requires users to re-authenticate. Plan before launch.
A connection that has stopped working shows up as `authorizationInvalid` or `insufficientScopes` in availability responses — [reconnecting a calendar](/core/troubleshooting#reconnect-a-calendar).
### Redirect URLs [#redirect-urls]
Configure your **production** URL in the Recal dashboard.
* Must match **exactly** in both Recal and your OAuth provider
* Dev/staging: override with `?redirectUrl=http://localhost:3000/callback`
# Microsoft Setup
URL: /core/oauth/microsoft
Jump to [Configure API Permissions](#2-configure-api-permissions), [Get Credentials](#3-obtain-client-id-and-secret), or [Add to Recal](#5-add-to-recal).
### 1. Register Application in Azure [#1-register-application-in-azure]
Go to [Azure Portal](https://portal.azure.com/) → Search **"App registrations"** → **+ New registration**:
* **Display name**: Your app name
* **Supported account types**: "Any organizational directory + personal accounts" (SaaS) or "This org only" (internal)
* **Redirect URI**: Web → `https://yourapp.com/auth/callback`
* Click **Register**
### 2. Configure API Permissions [#2-configure-api-permissions]
**API permissions** → **+ Add a permission** → **Microsoft Graph** → **Delegated permissions**:
* Add Calendar permissions (see [Scopes](#4-understanding-scopes-in-recal) below)
* For org apps: **Grant admin consent**
### 3. Obtain Client ID and Secret [#3-obtain-client-id-and-secret]
* **Client ID**: Overview page → Application (client) ID
* **Client Secret**: Certificates & secrets → + New client secret → Copy **Value** immediately (shown once)
### 4. Microsoft Scopes [#4-microsoft-scopes]
Recal maps to these Microsoft Graph permissions:
**`write` scope** - Read/write access to events
* `User.Read` - User's basic profile information
* `Calendars.ReadWrite` - Read/write access to calendars and events
* `Calendars.ReadWrite.Shared` - Read/write access to shared calendars
**`read` scope** - Read-only access to calendars and events
* `User.Read` - User's basic profile information
* `Calendars.Read` - Read-only access to calendars and events
**`free-busy` scope** - Read-only access to availability
* Same as `read` scope (Microsoft has no separate free-busy permission)
Request minimum scopes needed. Insufficient access returns `403` — re-authenticate with higher scope.
### 5. Add to Recal [#5-add-to-recal]
In Recal dashboard → **OAuth Credentials** → Add Client ID, Client Secret, and redirect URL to Microsoft card.
Redirect URL in Recal must exactly match the URI in Azure.
# Coding Agent Setup Prompt
URL: /core/oauth/setup-prompt
Registering an OAuth app means clicking through a console you may not know well. Paste one of
these prompts into a coding agent and it will walk you through that console one step at a time,
with Recal's requirements — the redirect URL, the permissions, what to copy — already filled in.
The Recal dashboard's setup checklist offers a shorter version of the same prompt with your
dashboard's own redirect URL substituted. This is the fuller one.
Each prompt uses the dashboard's hosted callback, `https://dash.recal.dev/oauth/`. That
address works for connecting calendars from the dashboard; if you run your own callback, replace
it — in the prompt and in Recal — before you start. Whatever you pick, the redirect URL registered
with the provider must match the one entered in Recal exactly.
```text
I am setting up Recal (a unified calendar API, https://recal.dev) and need to connect Google Calendar. Walk me through creating an OAuth app in the Google Cloud Console step by step, one step at a time, and wait for me to confirm before moving on. Ask me what I already have before you start.
Context about Recal you should assume:
- Recal is the OAuth client. My users grant it access to their Google Calendars through my own OAuth app; Recal stores the tokens and makes the calendar calls.
- Recal asks for one of three scopes and expands it into Google permissions itself. I do not configure scopes in Recal; the consent screen just has to permit them:
- free-busy: userinfo.email + calendar.freebusy (busy intervals only, no event details)
- read: userinfo.email + calendar.readonly
- write: userinfo.email + calendar.events + calendar.readonly
- The redirect URL I register in Google must be byte-identical to the one I enter in Recal. I will use the Recal dashboard's hosted page: https://dash.recal.dev/oauth/google
What I need at the end:
1. A Google Cloud project with the Google Calendar API enabled.
2. An OAuth consent screen. Tell me when to pick External (my customers are outside my Google Workspace) versus Internal, and which fields are required. Remind me that Testing mode expires refresh tokens after about 7 days and that I must publish to Production before launch.
3. An OAuth client ID of type Web application whose Authorized redirect URIs contains exactly the redirect URL above, character for character: same scheme, host and path, no trailing slash.
4. The Client ID and Client Secret of that client.
Then tell me to paste the client ID, the client secret and the same redirect URL into the Recal dashboard under OAuth Credentials, on the Google card, and save.
Done looks like: the redirect URL in the Google Cloud Console and in Recal are identical, and connecting a calendar from the Recal dashboard ends on a "Connected" page. If Google shows redirect_uri_mismatch, the two URLs differ. If a connection stops working after about a week, the consent screen is still in Testing mode.
```
```text
I am setting up Recal (a unified calendar API, https://recal.dev) and need to connect Microsoft Outlook calendars. Walk me through registering an application in the Azure portal (Microsoft Entra ID, App registrations) step by step, one step at a time, and wait for me to confirm before moving on. Ask me what I already have before you start.
Context about Recal you should assume:
- Recal is the OAuth client. My users grant it access to their Outlook calendars through my own app registration; Recal stores the tokens and makes the Microsoft Graph calls.
- Recal asks for one of three scopes and expands it into Microsoft Graph delegated permissions itself. The app registration just has to grant them:
- free-busy: User.Read + Calendars.Read (Graph has no free/busy-only permission, so this is the same as read)
- read: User.Read + Calendars.Read
- write: User.Read + Calendars.ReadWrite + Calendars.ReadWrite.Shared
- The redirect URI I register in Azure must be byte-identical to the one I enter in Recal. I will use the Recal dashboard's hosted page: https://dash.recal.dev/oauth/microsoft
What I need at the end:
1. An app registration. Tell me when to pick "Accounts in any organizational directory and personal Microsoft accounts" (my customers are on other tenants or use personal accounts) versus a single tenant.
2. A Web platform redirect URI set to exactly the redirect URL above, character for character: same scheme, host and path, no trailing slash.
3. The delegated Microsoft Graph permissions listed above added under API permissions, with admin consent granted if this is a single-tenant app.
4. The Application (client) ID from the Overview page, and a client secret from Certificates & secrets. Remind me to copy the secret's Value the moment it is created, because it is shown once.
Then tell me to paste the client ID, the client secret and the same redirect URL into the Recal dashboard under OAuth Credentials, on the Microsoft card, and save.
Done looks like: the redirect URI in Azure and in Recal are identical, and connecting a calendar from the Recal dashboard ends on a "Connected" page. If Microsoft shows AADSTS50011, the two URLs differ. If it shows AADSTS65001 or asks for admin approval, consent has not been granted for the permissions.
```
The manual walkthroughs cover the same ground without an agent: [Google setup](/core/oauth/google)
and [Microsoft setup](/core/oauth/microsoft). If a connection fails after everything is saved, see
[reconnecting a calendar](/core/troubleshooting#reconnect-a-calendar).
# Quick Start
URL: /core/quick-start
For direct API calls without the SDK, check out the [interactive API reference](https://api.recal.dev/v1/swagger).
## Setup [#setup]
### 1. Get Your API Key [#1-get-your-api-key]
[Sign up](https://dash.recal.dev/sign-up) → Dashboard → API Keys → Create new key
### 2. Configure OAuth [#2-configure-oauth]
Dashboard → OAuth Credentials → Add your provider credentials
Need OAuth credentials?
* [Google Calendar setup](/core/oauth/google)
* [Microsoft Outlook setup](/core/oauth/microsoft)
### 3. Install SDK [#3-install-sdk]
```bash
npm install recal-sdk
# or: bun add recal-sdk / yarn add recal-sdk
```
### 4. Initialize [#4-initialize]
```typescript
import { RecalClient } from 'recal-sdk'
const recal = new RecalClient({
token: "YOUR_API_KEY"
})
// Test connection
const orgs = await recal.organizations.listAll()
```
## First Integration [#first-integration]
### Create a User [#create-a-user]
```typescript
const user = await recal.users.create('user_123')
```
### Connect Calendar [#connect-calendar]
```typescript
// Generate OAuth link
const { url } = await recal.oauth.getLink('user_123', 'google')
// Redirect user to `url` → they authorize → callback with code and state
// Verify connection
await recal.oauth.verify(
'google',
code, // from callback
scope, // from callback
state // from callback
)
```
### Read Events [#read-events]
```typescript
const events = await recal.calendar.getEvents(
'user_123',
new Date('2024-01-01'),
new Date('2024-01-31')
)
```
## Next Steps [#next-steps]
Need help? Email [team@recal.dev](mailto:team@recal.dev)
# REST API
URL: /core/rest-api
For complete documentation with request/response schemas and interactive testing, visit the **[Swagger UI](https://api.recal.dev/v1/swagger)**.
Availability endpoints can answer partially; the Swagger schema links to [Troubleshooting](/core/troubleshooting) where it does.
## Base URL [#base-url]
```
https://api.recal.dev/v1
```
## Authentication [#authentication]
Use your API key in the `Authorization` header:
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.recal.dev/v1/users
```
Generate keys at [dash.recal.dev](https://dash.recal.dev) → API Keys
## Endpoints [#endpoints]
### Scheduling [#scheduling]
Find availability across users or organizations.
* `GET /v1/users/{userId}/scheduling`
* `GET /v1/organizations/{orgSlug}/scheduling`
Organization routes report connected members that could not be read; see [Troubleshooting](/core/troubleshooting#partial-results).
### Users [#users]
* `GET /v1/users` — List users
* `POST /v1/users` — Create user
* `GET /v1/users/{userId}` — Get details
* `PUT /v1/users/{userId}` — Update
* `DELETE /v1/users/{userId}` — Delete
### Organizations [#organizations]
Create workspaces to group users. Optional for B2C, essential for B2B multi-tenancy.
* `GET /v1/organizations` — List organizations
* `POST /v1/organizations` — Create organization
* `GET /v1/organizations/{orgSlug}` — Get organization details
* `PUT /v1/organizations/{orgSlug}` — Update organization
* `DELETE /v1/organizations/{orgSlug}` — Delete organization
### Calendar [#calendar]
* `GET /v1/users/{userId}/calendar/busy` — User busy periods
* `GET /v1/organizations/{orgSlug}/calendar/busy` — Organization busy periods
Organization routes report connected members that could not be read, and the user route reports calendars it could not read; see [Troubleshooting](/core/troubleshooting#partial-results).
### OAuth [#oauth]
Supported: Google Calendar, Microsoft Outlook
* `GET /v1/users/{userId}/oauth` — List connections
* `POST /v1/users/{userId}/oauth/{provider}/authorize` — Start OAuth
* `DELETE /v1/users/{userId}/oauth/{provider}` — Remove connection
#### OAuth Scopes [#oauth-scopes]
Recal offers three levels of access:
* **`write`** - Full calendar read/write access (create, update, delete events)
* **`read`** - Read-only access to calendars and events
* **`free-busy`** - Read-only access to availability information
`edit` is **deprecated** — still accepted as a synonym for `write`, but it will be removed in a future version. New integrations should request `write`.
When making API calls, Recal automatically validates scopes. If a user lacks required permissions, you'll receive a `403 Forbidden` response:
```json
{
"error": "Insufficient scopes for operation 'calendar.events.insert'. Required scope level: write. You need to request one of these scopes: ...",
"operation": "calendar.events.insert",
"validScopes": [
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events"
],
"data": null
}
```
See the [OAuth Setup Guide](/core/oauth) for detailed scope configuration.
## Example Request [#example-request]
```bash
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.recal.dev/v1/users
```
## Responses [#responses]
We're responding in the standardized API format:
```json
{
data: {
// The actual data payload
}
}
// or
{
data: null
error: string
}
// or, on availability endpoints that read several calendars or members
{
data: { /* everything that could be read */ },
failedCalendars: [ /* or failedUsers — what could not, each with a reason and message */ ]
}
```
The third form is a `200`. Three things always hold:
* Only endpoints that fan out over calendars or members carry a list.
* `data` keeps its ordinary shape — the list never moves inside it.
* The list is always present, `[]` when nothing failed, so `failedCalendars.length` needs no guard.
Availability routes can answer partially — see [Troubleshooting](/core/troubleshooting#partial-results).
## Next Steps [#next-steps]
# Troubleshooting
URL: /core/troubleshooting
Availability answers can come back incomplete. An authorization expires, a user un-subscribes from a
calendar, a provider throttles a request — and one of the calendars behind an answer cannot be read.
Recal returns what it could read and names what it could not, so the gap is something you can act on
instead of something that silently makes a busy person look free.
Every named failure carries a `reason` from a closed set of ten codes. If you already have one in
front of you, skip to the [reason reference](#reason-reference).
***
## Reconnect a calendar [#reconnect-a-calendar]
`authorizationInvalid` and `insufficientScopes` mean the stored authorization no longer lets Recal
read the calendar. Nothing in your code fixes either one — the user has to grant access again.
Send them back through the same link flow you used to connect them:
1. Get a fresh authorization URL — `GET /v1/users/{userId}/oauth/{provider}/link`, or
`recal.oauth.getAuthLink(userId, provider)`. For `insufficientScopes`, request `free-busy` or
higher.
2. Redirect the user to it and let them approve.
3. Exchange the code — `POST /v1/users/oauth/{provider}/verify`, or `recal.oauth.verifyCode(...)`.
Verifying **replaces** the stored connection, so there is no need to `DELETE` the old one first.
A Google OAuth app still in **testing mode** issues refresh tokens that expire after about seven
days. Every connection made through it reports `authorizationInvalid` a week later. Moving the app
to production before launch is the fix — see [Google setup](/core/oauth/google).
**What to show your user:** "We can't read your calendar any more. Reconnect it to keep your
availability up to date."
On the single-user routes these two are not partial answers at all: a dead authorization answers
**400** and insufficient scopes answers **403**. The partial form appears only on the organization
routes and the multi-user scheduling route.
***
## Partial results [#partial-results]
A partial answer is a **200**. `data` has its ordinary shape and holds everything that could be read;
a list beside it names everything that could not.
If a **connected** calendar or a **connected** member is not in `data`, it is in the list. A 200
never drops one silently.
Four routes can answer partially:
| Route | The list |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `GET /v1/users/{userId}/calendar/busy` | `failedCalendars` beside `data` |
| `GET /v1/organizations/{orgSlug}/calendar/busy` | `failedUsers` beside `data` |
| `GET /v1/organizations/{orgSlug}/scheduling` | `failedUsers` beside `data` |
| `POST /v1/users/scheduling` | `failedCalendars` on each `ok` entry; `reason` on each `error` entry that came from a calendar provider |
`GET` and `POST /v1/users/{userId}/scheduling` read one calendar, so there is nothing to be partial
about — they answer a status code instead.
One exception on the multi-user route: with `maxOverlaps > 0`, a calendar that cannot be read fails
that user's whole entry rather than trimming it, so you get a `status: 'error'` entry instead of an
`ok` one. A populated `failedCalendars` is a `maxOverlaps: 0` phenomenon.
### One user's busy times [#one-users-busy-times]
```json
{
"data": [
{ "start": "2026-01-05T09:00:00.000Z", "end": "2026-01-05T10:00:00.000Z" }
],
"failedCalendars": [
{
"calendarId": "old-team@group.calendar.google.com",
"provider": "google",
"reason": "notFound",
"message": "The calendar does not exist or is no longer subscribed"
}
]
}
```
```typescript
// Since recal-sdk 1.2.0 this method resolves to the envelope, not a bare array.
const { data, failedCalendars } = await recal.calendar.getBusyTimes('user_id', {
start: '2026-01-05T00:00:00Z',
end: '2026-01-06T00:00:00Z'
})
```
### An organization's busy times [#an-organizations-busy-times]
Each entry names the member by their `customId`. Its `reason` is the most severe of their calendars'
reasons, so you can switch on one field and drill into `failedCalendars` when you need the detail.
```json
{
"data": [
{ "start": "2026-01-05T09:00:00.000Z", "end": "2026-01-05T11:00:00.000Z" }
],
"failedUsers": [
{
"customId": "bob",
"reason": "authorizationInvalid",
"message": "The stored calendar authorization is no longer valid",
"failedCalendars": []
},
{
"customId": "carol",
"reason": "notFound",
"message": "The calendar does not exist or is no longer subscribed",
"failedCalendars": [
{
"calendarId": "old-team@group.calendar.google.com",
"provider": "google",
"reason": "notFound",
"message": "The calendar does not exist or is no longer subscribed"
}
]
}
]
}
```
The nested list is the difference between *some* and *none*:
* **`failedCalendars: []`** — nothing of that member was readable. They contributed no busy time at
all, so treat them as unknown, never as free. Bob is this case.
* **`failedCalendars` non-empty** — partial. `data` already holds the busy time from their other
calendars, and the entries name what is missing. Carol is this case.
`GET /v1/organizations/{orgSlug}/scheduling` carries `failedUsers` in exactly the same shape beside
its usual `{ availableSlots, options }`.
### Members with no connected calendar are skipped [#members-with-no-connected-calendar-are-skipped]
A member who has never connected a calendar, or who disconnected, is **not listed** — with or without
a `provider=` filter. Not being connected is a provisioning state you control and can read back
yourself, not a failure, so it is never a `reason`.
An organization that has not configured the provider at all is a different thing and *is* reported:
every one of its members comes back with `providerNotConfigured`. See
[your configuration](#your-configuration).
That means the lists tell you about connections that broke, not about connections that were never
made. To know who is connected:
```typescript
// Everyone in an organization, with their connections
const members = await recal.organizations.getMembers('acme-corp', {
include: ['oauthConnections']
})
// One user
const connections = await recal.oauth.list('user_id')
```
The one exception is `POST /v1/users/scheduling`, which has always named them: an unconnected user
comes back as `{ status: 'error', error: 'User has no connected calendars' }`, with no `reason`.
***
## What a missing calendar does to availability [#what-a-missing-calendar-does-to-availability]
Only the calendars that could be read contribute busy time. A calendar that failed contributes
**nothing** — it is left out of the calculation rather than guessed at.
On the busy routes that is simply what you asked for: you get the busy times we could see, and
`failedCalendars` names the rest.
On the **slot** routes it has a direction worth knowing — but only where they answer partially at
all. Slots are computed from the busy time we found, so a calendar we could not read cannot narrow
them:
If the conflict lived on the calendar that failed, the slot still looks free. A non-empty
`failedCalendars` or `failedUsers` means the slots beside it may be **wider than reality** — never
narrower.
This is deliberate, and the alternative is worse. Blocking the whole window for a calendar we could
not read would make one broken authorization zero out that user's availability entirely — and a
broken authorization persists until somebody reconnects it, so the user would quietly become
unbookable for days rather than for one request. An answer you can audit beats no answer at all.
What that means in practice depends on what a collision costs you:
| If a double-booking is… | Do this |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Recoverable (internal scheduling, easy to move) | Book, and surface the reconnect prompt from `failedCalendars` |
| Expensive (customer-facing, paid, hard to move) | Treat that user's slots as provisional — confirm out of band, or withhold them until the calendar reconnects |
Either way the decision is yours to make per request, which is why the list is in the response rather
than being resolved for you.
**Every calendar failed.** There is nothing to be optimistic with, so the route answers a status code
instead of a 200 — see [Whole-request failures](#whole-request-failures).
**`maxOverlaps > 0` on the multi-user route.** That path reads full event times rather than busy
blocks, and one unreadable calendar fails the user's whole entry instead of trimming it — you get a
`status: 'error'` entry, not optimistic slots. It fails closed; the optimism above is a
`maxOverlaps: 0` phenomenon.
Worth knowing if you are porting from another provider: this is the same trade Cronofy makes, and the
opposite of Microsoft Graph's `findMeetingTimes`, which prices an attendee of unknown availability at
49% against a 50% threshold and so suppresses the suggestion entirely. Recal answers and flags; Graph
withholds. Neither is wrong, but the contract differs, so do not assume a slot from Recal has been
checked against every calendar.
***
## Detecting a partial answer [#detecting-a-partial-answer]
Both lists are **always present** — `[]` when nothing failed — so you can read `.length` without
a guard.
```typescript
const { data, failedCalendars } = await recal.calendar.getBusyTimes(userId, range)
if (failedCalendars.length > 0) {
// data is incomplete; decide what to do before you book against it
}
const { data: orgBusy, failedUsers } = await recal.organizations.getBusyTimes(slug, range)
for (const user of failedUsers) {
switch (user.reason) {
case 'authorizationInvalid':
case 'insufficientScopes':
promptReconnect(user.customId)
break
default:
logForLater(user)
}
}
```
On the multi-user scheduling route, check `status` on each entry and `failedCalendars` on the `ok`
ones.
An empty `data` with a non-empty list means *nothing could be read*, not *nothing is booked*.
Booking flows should fail closed: show the slot as unavailable, or surface the reconnect prompt,
rather than offering a time you never actually checked.
Switch on `reason`; it is a closed union and safe to branch on. `message` is a fixed English sentence
for your logs — it is not written for your end users, and it never contains calendar ids, provider
text or anything else that varies per request.
***
## Stale calendar ids [#stale-calendar-ids]
`notFound` and `accessDenied` mean one calendar in the list could not be read while the others were.
These are the everyday partials, and how you fix one depends on where the id came from.
**You passed explicit `calendarIds`.** The id is stale — drop it from whatever you store, and re-list
the user's calendars with `GET /v1/users/{userId}/calendar` to see what is actually there.
**You did not pass `calendarIds`.** Recal read the user's own subscribed list, which is cached for an
hour. A calendar the user removed keeps appearing until that clears, so a `notFound` on this path is
usually transient; if it persists past an hour, the user un-subscribed and nothing needs fixing.
`accessDenied` is a sharing problem rather than a stale one: the calendar exists but is no longer
shared with this user.
`mailboxUnavailable` looks similar and is not: it means the user has no calendar mailbox on that
provider in the first place — an Outlook account with no Exchange Online mailbox behind it. There is
nothing to re-share and nothing to drop. Their Microsoft administrator has to provision or licence
the mailbox; until then, do not query that provider for that user.
**What to show your user:** "We can't read the calendar *Team events*. Ask its owner to share it
again, or remove it." For `mailboxUnavailable`, tell them their Outlook account has no calendar yet.
***
## Transient failures [#transient-failures]
`rateLimited` and `providerError` are the provider's side, not yours. The calendar is fine and the
authorization is fine; the request did not get through.
Retry with backoff — the [retry helper](/sdk/javascript/error-handling#retry-with-exponential-backoff)
on the error-handling page works here too, driven by the list instead of a thrown error. If
`providerError` persists across retries, [contact support](mailto:hello@recal.dev).
There is nothing useful to show an end user for either. Keep displaying the last good answer and
retry behind the scenes.
***
## Your configuration [#your-configuration]
`providerNotConfigured`, `invalidCalendarId` and `tooManyCalendars` are fixed by you, not by your
user.
* **`providerNotConfigured`** — your organization holds no OAuth credentials for that provider, so
nothing can be read through it. Add them in the [dashboard](/core/dashboard).
* **`invalidCalendarId`** — the id is not well-formed for that provider. Usually a Google id sent to
Microsoft, or a truncated one. Fix the id.
* **`tooManyCalendars`** — the user is subscribed to more calendars than one lookup can read. Pass
explicit `calendarIds` for the ones you actually care about.
None of the three has anything to show an end user.
It is reported for **every** member of the organization, on every request, for as long as the
credentials are missing — an org-wide fault dressed as a per-member failure. Narrowing with
`provider=` does not sidestep it: naming an unconfigured provider fails the whole request rather
than trimming it to what you set up.
***
## Reason reference [#reason-reference]
| `reason` | What happened | Who fixes it | What to show your user | How to resolve it |
| ----------------------- | ---------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
| `authorizationInvalid` | The stored authorization was rejected or could not be refreshed | Your user | "We can't read your calendar any more. Reconnect it to keep your availability up to date." | [Reconnect](#reconnect-a-calendar) through the link flow |
| `insufficientScopes` | The authorization does not include permission to read busy times | Your user | Same reconnect prompt | Reconnect requesting `free-busy` or higher |
| `providerNotConfigured` | Your organization has no OAuth credentials for that provider | You | Nothing | Add the provider's credentials in the [dashboard](/core/dashboard) |
| `notFound` | The calendar does not exist or is no longer subscribed | You, or nobody | "We can't read the calendar *Team events*." | Drop the id, or wait out the one-hour calendar-list cache |
| `accessDenied` | The calendar is not shared with this user | Your user | "Ask its owner to share *Team events* again, or remove it." | Re-share the calendar, or drop the id |
| `mailboxUnavailable` | The user has no calendar mailbox on that provider at all | Your user's Microsoft admin | "Your Outlook account doesn't have a calendar yet." | Have the mailbox provisioned or licensed — a re-share cannot fix it — or stop querying that provider for them |
| `invalidCalendarId` | The id is not valid for that provider | You | Nothing | Fix the id you are sending |
| `tooManyCalendars` | The user has more calendars than one lookup can read | You | Nothing | Pass explicit `calendarIds` |
| `rateLimited` | The provider throttled the request | Nobody | Nothing — show the last good answer | Retry with backoff |
| `providerError` | The provider could not be read | Nobody | Nothing — show the last good answer | Retry with backoff; if it persists, [contact support](mailto:hello@recal.dev) |
The set is closed: a code is never renamed or removed once published, and a `switch` over these ten
values is complete today. New codes would be added in a future API version.
***
## Whole-request failures [#whole-request-failures]
When *nothing* could be read there is no partial answer to give, so `GET /v1/users/{userId}/calendar/busy`
answers a status code instead of a 200. A status always means the whole lookup failed — never that
part of it did.
| Status | When |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` | Invalid parameters; a dead authorization; the user has too many calendars; none of the requested providers is connected, or your organization has no credentials for them; every requested calendar was `invalidCalendarId` |
| `401` | The provider itself rejected the stored token |
| `403` | Insufficient scopes; every requested calendar was `accessDenied` |
| `404` | The user does not exist; every requested calendar was `notFound` |
| `429` | The provider throttled the whole lookup; every requested calendar was `rateLimited`. The whole-lookup form carries a `Retry-After` header; the per-calendar form does not |
| `502` | The provider could not be reached or answered with something unreadable; every requested calendar was `providerError` |
`401` on these routes means the **provider** rejected the stored token. An expired or unrefreshable
authorization — by far the most common failure — answers `400`. Both lead to the same place:
[reconnect the calendar](#reconnect-a-calendar).
The organization routes do not have this table. They answer `200` with `failedUsers` whenever the
organization itself resolves, whatever happened to its members.
In the SDK these arrive as a thrown `RecalError` carrying `statusCode` — see
[Error Handling](/sdk/javascript/error-handling).
***
## Related [#related]
* See [Error Handling](/sdk/javascript/error-handling) for status codes and retries in the SDK
* See [OAuth Setup](/core/oauth) for scopes and the connection flow
* See [Calendar & Availability](/sdk/javascript/free-busy) for busy-time queries
* See [Organizations](/sdk/javascript/organizations) for team-wide availability
# Webhooks
URL: /core/webhooks
Webhook support is actively being built. Google Calendar webhooks are implemented, with Microsoft Outlook coming soon. Our SDK will provide typesafe webhook handlers to make integration seamless.
## What are Webhooks? [#what-are-webhooks]
Think of webhooks as a notification system for your calendar. Instead of constantly checking if something changed, Recal sends you a message the moment an event is created, updated, or deleted.
**Real-world use cases:**
* Sync calendar events to your CRM in real-time
* Trigger automated workflows when meetings are scheduled
* Update dashboards instantly when availability changes
* Send notifications to your team when events are modified
## How It Works [#how-it-works]
```mermaid
graph LR
A[Google Calendar] -->|Event Change| B[Recal API]
B -->|Processes & Formats| C[Your Webhook URL]
C -->|Receives Clean Event Data| D[Your Application]
style B fill:#4f46e5,stroke:#4338ca,color:#fff
style A fill:#4285f4,stroke:#1a73e8,color:#fff
```
### What Recal Handles For You [#what-recal-handles-for-you]
The beauty of Recal's webhook system is that we handle all the complex Google Calendar API interactions so you don't have to.
**Without Recal:**
* Register watch channels with Google Calendar API
* Handle channel expiration (max 30 days)
* Renew channels before they expire
* Parse cryptic notification headers
* Fetch actual event changes using sync tokens
* Handle rate limits and retries
**With Recal:**
* Just provide your webhook URL
* Receive clean, parsed event data
* We handle everything else automatically
## Supported Events [#supported-events]
Recal sends notifications for three types of calendar events:
**Triggered when:** A new calendar event is created
**Example payload:**
```json
{
"type": "event.created",
"timestamp": "2024-01-15T10:30:00Z",
"event": {
"id": "evt_1234567890",
"summary": "Team Standup",
"start": "2024-01-16T09:00:00Z",
"end": "2024-01-16T09:30:00Z",
"attendees": ["alice@example.com", "bob@example.com"]
}
}
```
**Triggered when:** An existing calendar event is modified
**Example payload:**
```json
{
"type": "event.updated",
"timestamp": "2024-01-15T10:30:00Z",
"event": {
"id": "evt_1234567890",
"summary": "Team Standup (Rescheduled)",
"start": "2024-01-16T14:00:00Z",
"end": "2024-01-16T14:30:00Z",
"attendees": ["alice@example.com", "bob@example.com"]
},
"changes": ["start", "end", "summary"]
}
```
**Triggered when:** A calendar event is removed
**Example payload:**
```json
{
"type": "event.deleted",
"timestamp": "2024-01-15T10:30:00Z",
"event": {
"id": "evt_1234567890"
}
}
```
## Setting Up Webhooks [#setting-up-webhooks]
### 1. Navigate to Webhooks Settings [#1-navigate-to-webhooks-settings]
In your Recal dashboard, go to **Settings** → **Webhooks** (or navigate to `/[your-org]/webhooks`)
### 2. Add Your Webhook URL [#2-add-your-webhook-url]
Click **Add Webhook** and provide:
* **Webhook URL**: Your HTTPS endpoint (must use SSL)
* **Event Types**: Select which events you want to receive
Your webhook URL must use HTTPS with a valid SSL certificate. HTTP endpoints are not supported for security reasons.
### 3. Test Your Integration [#3-test-your-integration]
Once configured, Recal will start sending event notifications to your endpoint. You can view delivery logs and retry failed attempts from the dashboard.
## SDK Integration (Coming Soon) [#sdk-integration-coming-soon]
We're building a typesafe SDK handler to make webhook integration even easier:
```typescript
import { RecalWebhookHandler } from '@recal/sdk'
const handler = new RecalWebhookHandler({
secret: process.env.RECAL_WEBHOOK_SECRET
})
// TypeScript knows the exact event shape!
handler.on('event.created', (event) => {
console.log(`New event: ${event.summary}`)
console.log(`Starts at: ${event.start}`)
})
handler.on('event.updated', (event) => {
console.log(`Updated fields: ${event.changes.join(', ')}`)
})
handler.on('event.deleted', (event) => {
console.log(`Deleted event: ${event.id}`)
})
// Express example
app.post('/webhooks/recal', async (req, res) => {
await handler.handle(req.body, req.headers)
res.sendStatus(200)
})
```
The SDK webhook handler is currently being developed. It will provide automatic signature verification, type safety, and easy event handling. Star our [GitHub repo](https://github.com/recalai/recal) to get notified when it's released!
## Provider Support [#provider-support]
📅
Google Calendar
Live
Full webhook support with automatic watch channel management
📧
Microsoft Outlook
Coming Soon
Microsoft Graph API webhook integration in development
## Best Practices [#best-practices]
### Respond Quickly [#respond-quickly]
Your webhook endpoint should respond within 5 seconds. If you need to do heavy processing, acknowledge the webhook immediately and process asynchronously:
```typescript
app.post('/webhooks/recal', async (req, res) => {
// Acknowledge immediately
res.sendStatus(200)
// Process asynchronously
processWebhook(req.body).catch(console.error)
})
```
### Handle Idempotency [#handle-idempotency]
The same event might be delivered multiple times (e.g., during retries). Use the event ID to ensure you only process each event once:
```typescript
const processedEvents = new Set()
handler.on('event.created', async (event) => {
if (processedEvents.has(event.id)) {
console.log('Already processed, skipping')
return
}
processedEvents.add(event.id)
await saveToDatabase(event)
})
```
### Verify Signatures (Coming Soon) [#verify-signatures-coming-soon]
When the SDK is released, always verify webhook signatures to ensure requests are genuinely from Recal:
```typescript
const handler = new RecalWebhookHandler({
secret: process.env.RECAL_WEBHOOK_SECRET,
verifySignature: true // Recommended for production
})
```
### Monitor Delivery Logs [#monitor-delivery-logs]
Use the Recal dashboard to monitor webhook deliveries. You can:
* View successful and failed attempts
* See response codes and error messages
* Manually retry failed deliveries
* Debug payload and response data
## Security Considerations [#security-considerations]
1. **Use HTTPS Only**: Never expose webhook endpoints over HTTP
2. **Verify Signatures**: Use the SDK's built-in verification (when available)
3. **Validate Payloads**: Always validate incoming data structure
4. **Rate Limit**: Implement rate limiting on your endpoint
5. **Keep Secrets Safe**: Store webhook secrets in environment variables
## Troubleshooting [#troubleshooting]
### Webhooks Not Arriving [#webhooks-not-arriving]
1. Check your webhook URL is accessible from the internet
2. Verify your SSL certificate is valid (test with [SSL Labs](https://www.ssllabs.com/ssltest/))
3. Ensure your endpoint returns 2xx status codes
4. Check the delivery logs in the Recal dashboard
### Receiving Duplicate Events [#receiving-duplicate-events]
This is normal behavior. Implement idempotency using event IDs to handle duplicates gracefully.
## What's Next? [#whats-next]
* **[Dashboard Guide](/core/dashboard)** - Learn how to manage webhooks in the UI
* **[API Reference](https://api.recal.dev/v1/swagger)** - Interactive API documentation
* **[OAuth Setup](/core/oauth/google)** - Connect Google Calendar to receive webhooks
# Delete Organization
URL: /rest-api/endpoints/deleteV1OrganizationsByOrgSlug
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Remove Members
URL: /rest-api/endpoints/deleteV1OrganizationsByOrgSlugMembers
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Delete User
URL: /rest-api/endpoints/deleteV1UsersByUserId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Delete Event
URL: /rest-api/endpoints/deleteV1UsersByUserIdCalendarEventsByProviderByCalendarIdByEventId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Delete Unified Event
URL: /rest-api/endpoints/deleteV1UsersByUserIdCalendarEventsMetaByMetaId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Delete OAuth Connection
URL: /rest-api/endpoints/deleteV1UsersByUserIdOauthByProvider
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List Organizations
URL: /rest-api/endpoints/getV1Organizations
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Organization
URL: /rest-api/endpoints/getV1OrganizationsByOrgSlug
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Organization Availability
URL: /rest-api/endpoints/getV1OrganizationsByOrgSlugCalendarBusy
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List Members
URL: /rest-api/endpoints/getV1OrganizationsByOrgSlugMembers
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Organization Scheduling
URL: /rest-api/endpoints/getV1OrganizationsByOrgSlugScheduling
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List Users
URL: /rest-api/endpoints/getV1Users
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get User
URL: /rest-api/endpoints/getV1UsersByUserId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List Calendars
URL: /rest-api/endpoints/getV1UsersByUserIdCalendar
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get User Availability
URL: /rest-api/endpoints/getV1UsersByUserIdCalendarBusy
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List Events
URL: /rest-api/endpoints/getV1UsersByUserIdCalendarEvents
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Event
URL: /rest-api/endpoints/getV1UsersByUserIdCalendarEventsByProviderByCalendarIdByEventId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Unified Event
URL: /rest-api/endpoints/getV1UsersByUserIdCalendarEventsMetaByMetaId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List OAuth Connections
URL: /rest-api/endpoints/getV1UsersByUserIdOauth
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get OAuth Connection
URL: /rest-api/endpoints/getV1UsersByUserIdOauthByProvider
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get OAuth Link
URL: /rest-api/endpoints/getV1UsersByUserIdOauthByProviderLink
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get OAuth Token
URL: /rest-api/endpoints/getV1UsersByUserIdOauthByProviderToken
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get OAuth Links
URL: /rest-api/endpoints/getV1UsersByUserIdOauthLinks
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# List User Organizations
URL: /rest-api/endpoints/getV1UsersByUserIdOrganizations
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get User Scheduling (Basic)
URL: /rest-api/endpoints/getV1UsersByUserIdScheduling
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create Organization
URL: /rest-api/endpoints/postV1Organizations
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Add Members
URL: /rest-api/endpoints/postV1OrganizationsByOrgSlugMembers
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create User
URL: /rest-api/endpoints/postV1Users
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create Event
URL: /rest-api/endpoints/postV1UsersByUserIdCalendarEventsByProviderByCalendarId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create Unified Event
URL: /rest-api/endpoints/postV1UsersByUserIdCalendarEventsMeta
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Create OAuth Connection
URL: /rest-api/endpoints/postV1UsersByUserIdOauthByProvider
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get User Scheduling (Advanced)
URL: /rest-api/endpoints/postV1UsersByUserIdScheduling
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Verify OAuth Code
URL: /rest-api/endpoints/postV1UsersOauthByProviderVerify
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Get Scheduling from Busy Data
URL: /rest-api/endpoints/postV1UsersScheduling
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Update Organization
URL: /rest-api/endpoints/putV1OrganizationsByOrgSlug
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Update User
URL: /rest-api/endpoints/putV1UsersByUserId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Update Event
URL: /rest-api/endpoints/putV1UsersByUserIdCalendarEventsByProviderByCalendarIdByEventId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Update Unified Event
URL: /rest-api/endpoints/putV1UsersByUserIdCalendarEventsMetaByMetaId
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
# Error Handling
URL: /sdk/javascript/error-handling
## Understanding Error Handling [#understanding-error-handling]
The Recal SDK provides a comprehensive error handling system through the `RecalError` class. All SDK methods throw typed errors that you can catch and handle appropriately in your application.
***
## RecalError Class [#recalerror-class]
The SDK uses a custom `RecalError` class that extends the native JavaScript `Error` with additional properties:
```typescript
class RecalError extends Error {
statusCode?: number // HTTP status code (404, 400, 500, etc.)
details?: unknown // Additional error details from the API
}
```
***
## Basic Error Handling [#basic-error-handling]
Wrap SDK calls in try-catch blocks to handle errors:
```typescript
import { Recal, RecalError } from 'recal-sdk'
const recal = new Recal({ token: process.env.RECAL_TOKEN })
try {
const user = await recal.users.get('user_123')
console.log('User found:', user)
} catch (error) {
if (error instanceof RecalError) {
console.error('Recal API Error:', error.message)
console.error('Status Code:', error.statusCode)
console.error('Details:', error.details)
} else {
console.error('Unexpected error:', error)
}
}
```
***
## Common Error Status Codes [#common-error-status-codes]
### 400 Bad Request [#400-bad-request]
Invalid request parameters or missing required fields.
```typescript
try {
await recal.events.createEvent('user_id', 'google', 'primary', {
subject: 'Meeting',
// Missing required 'start' and 'end' fields
})
} catch (error) {
if (error instanceof RecalError && error.statusCode === 400) {
console.error('Invalid request:', error.message)
// Handle validation errors
}
}
```
### 401 Unauthorized [#401-unauthorized]
Invalid or missing API token.
```typescript
const recal = new Recal({ token: 'invalid_token' })
try {
await recal.users.list()
} catch (error) {
if (error instanceof RecalError && error.statusCode === 401) {
console.error('Authentication failed - check your API token')
// Prompt user to re-authenticate or check token
}
}
```
### 404 Not Found [#404-not-found]
Resource doesn't exist (user, organization, event, etc.).
```typescript
try {
await recal.users.get('nonexistent_user')
} catch (error) {
if (error instanceof RecalError && error.statusCode === 404) {
console.error('User not found')
// Handle missing resource
}
}
```
### 429 Too Many Requests [#429-too-many-requests]
Rate limit exceeded.
```typescript
try {
await recal.calendar.listEvents('user_id', {
start: '2024-01-01T00:00:00Z',
end: '2024-12-31T23:59:59Z'
})
} catch (error) {
if (error instanceof RecalError && error.statusCode === 429) {
console.error('Rate limit exceeded - please retry later')
// Implement exponential backoff
}
}
```
### 500 Internal Server Error [#500-internal-server-error]
Server-side error.
```typescript
try {
await recal.oauth.verifyCode('google', { code: 'auth_code', state: 'state' })
} catch (error) {
if (error instanceof RecalError && error.statusCode === 500) {
console.error('Server error - please try again')
// Log error and notify monitoring system
}
}
```
***
## Error Handling Patterns [#error-handling-patterns]
### Centralized Error Handler [#centralized-error-handler]
Create a reusable error handler for consistent error handling:
```typescript
function handleRecalError(error: unknown, context: string) {
if (error instanceof RecalError) {
console.error(`[${context}] Recal API Error:`, {
message: error.message,
statusCode: error.statusCode,
details: error.details
})
// Handle specific status codes
switch (error.statusCode) {
case 400:
return { error: 'Invalid request', retry: false }
case 401:
return { error: 'Authentication failed', retry: false }
case 404:
return { error: 'Resource not found', retry: false }
case 429:
return { error: 'Rate limit exceeded', retry: true }
case 500:
return { error: 'Server error', retry: true }
default:
return { error: 'Unknown error', retry: false }
}
}
console.error(`[${context}] Unexpected error:`, error)
return { error: 'Unexpected error', retry: false }
}
// Usage
try {
await recal.users.create('user_123')
} catch (error) {
const result = handleRecalError(error, 'User Creation')
if (result.retry) {
// Implement retry logic
}
}
```
### Retry with Exponential Backoff [#retry-with-exponential-backoff]
Handle transient errors with automatic retries:
```typescript
async function withRetry(
fn: () => Promise,
maxRetries = 3,
initialDelay = 1000
): Promise {
let lastError: Error
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn()
} catch (error) {
lastError = error as Error
// Only retry on specific errors
if (error instanceof RecalError) {
const shouldRetry = [429, 500, 503].includes(error.statusCode || 0)
if (!shouldRetry || attempt === maxRetries - 1) {
throw error
}
const delay = initialDelay * Math.pow(2, attempt)
console.log(`Retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`)
await new Promise(resolve => setTimeout(resolve, delay))
} else {
throw error
}
}
}
throw lastError!
}
// Usage
const user = await withRetry(() => recal.users.get('user_123'))
```
### Graceful Degradation [#graceful-degradation]
Handle errors gracefully without breaking your application:
```typescript
async function getUserCalendars(userId: string) {
try {
return await recal.calendar.list(userId)
} catch (error) {
if (error instanceof RecalError) {
console.warn('Failed to fetch calendars:', error.message)
return [] // Return empty array as fallback
}
throw error
}
}
```
***
## Partial results are not errors [#partial-results-are-not-errors]
The availability methods can answer *incompletely* — some calendars read, some not. That is a `200`,
so no `RecalError` is thrown and a try-catch will never see it. The gap arrives as data instead:
```typescript
const { data, failedCalendars } = await recal.calendar.getBusyTimes('user_id', range)
if (failedCalendars.length > 0) {
// `data` covers only the calendars we could read
for (const calendar of failedCalendars) {
switch (calendar.reason) {
case 'authorizationInvalid':
case 'insufficientScopes':
await promptReconnect('user_id', calendar.provider)
break
case 'rateLimited':
case 'providerError':
scheduleRetry()
break
default:
console.warn(`Skipped ${calendar.calendarId}: ${calendar.message}`)
}
}
}
```
The organization methods carry `failedUsers` in the same position, and `getMultiUserSlots()` carries
`failedCalendars` on each `ok` entry plus an optional `reason` on each `error` entry.
Three things to know before you write the branch:
* **Both lists are always present**, `[]` when nothing failed — no optional-chaining needed.
* **Switch on `reason`, not `message`.** `reason` is a closed union of ten values; `message` is a
fixed sentence meant for your logs.
* **Empty `data` plus a non-empty list is not "available".** Fail closed in anything that books.
See [Troubleshooting](/core/troubleshooting) for what each `reason` means and what to show your user.
***
## Best Practices [#best-practices]
1. **Always Use Try-Catch**: Wrap all SDK calls in try-catch blocks
2. **Check Error Types**: Use `instanceof RecalError` to identify SDK errors
3. **Log Error Details**: Include `statusCode` and `details` in logs for debugging
4. **Handle Specific Codes**: Implement different logic for different status codes
5. **Implement Retries**: Retry transient errors (429, 500) with exponential backoff
6. **User-Friendly Messages**: Convert technical errors to user-friendly messages
7. **Monitor Errors**: Track error rates and patterns in your monitoring system
8. **Validate Input**: Catch validation errors early before making API calls
***
## Type Safety [#type-safety]
TypeScript provides type checking for error handling:
```typescript
import { Recal, RecalError } from 'recal-sdk'
async function safeUserFetch(userId: string) {
const recal = new Recal({ token: process.env.RECAL_TOKEN })
try {
const user = await recal.users.get(userId)
return { success: true, data: user }
} catch (error) {
// Type guard ensures proper error handling
if (error instanceof RecalError) {
return {
success: false,
error: error.message,
statusCode: error.statusCode
}
}
return { success: false, error: 'Unknown error' }
}
}
```
***
## Related [#related]
* See [Users](/sdk/javascript/users) for user-specific operations
* See [Events](/sdk/javascript/events) for event-specific operations
* See [OAuth](/sdk/javascript/oauth) for OAuth-specific error handling
* See [Troubleshooting](/core/troubleshooting) for partial availability answers and the `reason` codes
# Events
URL: /sdk/javascript/events
## Understanding Event Operations [#understanding-event-operations]
The Events API provides comprehensive event management across multiple calendar providers.
Whether you need to create a single event in a specific calendar or synchronize events across all connected providers,
this API handles the complexity of working with Google Calendar and Microsoft Outlook.
### Key Concepts: [#key-concepts]
**Provider-Specific Events**: Individual calendar entries created, read, updated, or deleted in a specific calendar (Google or Microsoft).
**Meta Events**: Unified calendar entries that are created, updated, or deleted across **all** connected calendar providers simultaneously, ensuring perfect synchronization.
***
## Provider-Specific Operations [#provider-specific-operations]
Use these methods when you need to interact with a specific calendar provider.
**Note:** To list/query existing events, see [Calendar & Availability](/sdk/javascript/free-busy#list-events).
### Create Event [#create-event]
```typescript
const event = await recal.events.createEvent(
'user_id',
'google',
'primary',
{
subject: 'Team Meeting',
description: 'Weekly sync',
start: '2024-01-15T10:00:00Z',
end: '2024-01-15T11:00:00Z',
attendees: [
{ email: 'colleague@company.com' }
],
meeting: true // Automatically creates Google Meet/Teams link
}
)
console.log(event.id) // Provider-specific event ID
console.log(event.meeting?.url) // Meeting link if meeting: true
```
### Get Event [#get-event]
```typescript
// Get an existing event from a specific calendar
const event = await recal.events.getEvent(
'user_id',
'google',
'primary',
'event_id'
)
```
### Update Event [#update-event]
```typescript
// Update an existing event in a specific calendar
const updated = await recal.events.updateEvent(
'user_id',
'google',
'primary',
'event_id',
{
subject: 'Updated Meeting Title',
description: 'Updated description',
start: '2024-01-15T11:00:00Z',
end: '2024-01-15T12:00:00Z'
}
)
```
### Delete Event [#delete-event]
```typescript
// Delete an event from a specific calendar
await recal.events.deleteEvent(
'user_id',
'google',
'primary',
'event_id'
)
```
***
## Cross-Calendar Operations (Meta Events) [#cross-calendar-operations-meta-events]
Meta events provide powerful cross-platform synchronization, ensuring events appear across all connected calendar providers simultaneously.
### Create Meta Event [#create-meta-event]
```typescript
// Create event across ALL connected calendars (default behavior)
const metaEvent = await recal.events.createMetaEvent(
'user_id',
{
subject: 'Cross-platform Meeting',
start: '2024-01-20T15:00:00Z',
end: '2024-01-20T16:00:00Z',
attendees: [
{ email: 'team@example.com' }
],
meeting: true
}
)
console.log(metaEvent.metaId) // Unique ID across all providers
// Or specify which providers to use
const metaEventSpecific = await recal.events.createMetaEvent(
'user_id',
{
subject: 'Selective Sync Meeting',
start: '2024-01-20T15:00:00Z',
end: '2024-01-20T16:00:00Z'
},
{
provider: ['google', 'microsoft'], // Only these providers
sendNotifications: true // Send email notifications
}
)
```
### Get Meta Event [#get-meta-event]
```typescript
// Retrieve event data from all connected calendars
const metaEvent = await recal.events.getMetaEvent(
'user_id',
'meta_id_123'
)
// Or filter by provider
const metaEventFiltered = await recal.events.getMetaEvent(
'user_id',
'meta_id_123',
{
provider: ['google']
}
)
```
### Update Meta Event [#update-meta-event]
```typescript
// Update across ALL connected calendars
await recal.events.updateMetaEvent(
'user_id',
'meta_id_123',
{
subject: 'Updated Cross-Platform Title',
start: '2024-01-20T16:00:00Z',
end: '2024-01-20T17:00:00Z'
}
)
// Or update with options
await recal.events.updateMetaEvent(
'user_id',
'meta_id_123',
{
subject: 'Updated Title'
},
{
provider: ['microsoft'], // Only update Microsoft calendars
sendNotifications: false
}
)
```
### Delete Meta Event [#delete-meta-event]
```typescript
// Delete from ALL connected calendars
await recal.events.deleteMetaEvent(
'user_id',
'meta_id_123'
)
// Or delete selectively
await recal.events.deleteMetaEvent(
'user_id',
'meta_id_123',
{
provider: ['google'] // Only delete from Google calendars
}
)
```
***
## Event Properties [#event-properties]
All events support the following properties:
```typescript
interface CreateEvent {
subject?: string // Event title
description?: string // Event description (HTML supported)
start: string // ISO 8601 timestamp
end: string // ISO 8601 timestamp
location?: string // Location or address
attendees?: Attendee[] // Array of { email: string }
meeting?: boolean // Auto-create meeting link (Google Meet/Teams)
}
```
***
## Best Practices [#best-practices]
1. **Use Meta Events for Sync**: When users have multiple calendars, use meta events to keep them synchronized
2. **Include Meeting Links**: Set `meeting: true` to automatically create Google Meet or Teams links
3. **Handle Timezones**: Always use ISO 8601 format with timezone information
4. **Validate Attendees**: Ensure email addresses are valid before creating events
5. **Check OAuth Permissions**: Ensure users have granted `write` scope for write operations
***
## Related [#related]
* See [Error Handling](/sdk/javascript/error-handling) for handling SDK errors
* See [Calendar & Availability](/sdk/javascript/free-busy) for querying events
* See [OAuth](/sdk/javascript/oauth) for managing calendar connections
# Calendar & Availability
URL: /sdk/javascript/free-busy
## Understanding Calendar Queries [#understanding-calendar-queries]
The Calendar API provides read-only access to user calendars and availability information across multiple providers.
Use these methods to list calendars, query events, and check busy times for scheduling applications.
***
## List Calendars [#list-calendars]
Get all calendars connected to a user across their calendar providers.
```typescript
// List all calendars
const calendars = await recal.calendar.list('user_id')
// Filter by provider
const googleCalendars = await recal.calendar.list('user_id', {
provider: 'google'
})
const microsoftCalendars = await recal.calendar.list('user_id', {
provider: 'microsoft'
})
```
Each calendar includes:
* `id`: Provider-specific calendar ID
* `name`: Calendar display name
* `primary`: Whether this is the user's primary calendar
* `backgroundColor`: Calendar color
* `timeZone`: Calendar timezone (e.g., "America/New\_York")
* `accessRole`: User's access level (`owner`, `writer`, `reader`, `freeBusyReader`)
***
## List Events [#list-events]
Retrieve events from a user's calendars within a date range.
```typescript
// List all events in a date range
const events = await recal.calendar.listEvents('user_id', {
start: '2024-01-01T00:00:00Z',
end: '2024-01-31T23:59:59Z'
})
// Filter by provider
const googleEvents = await recal.calendar.listEvents('user_id', {
start: '2024-01-01T00:00:00Z',
end: '2024-01-31T23:59:59Z',
provider: 'google'
})
// Specify timezone for results
const eventsInET = await recal.calendar.listEvents('user_id', {
start: '2024-01-01T00:00:00Z',
end: '2024-01-31T23:59:59Z',
provider: ['google', 'microsoft'],
timeZone: 'America/New_York'
})
```
**Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `provider` (optional): Filter by `'google'`, `'microsoft'`, or array `['google', 'microsoft']`
* `timeZone` (optional): Return results in specific timezone
***
## Get Busy Times [#get-busy-times]
Query when a user is busy/unavailable based on their calendar events.
```typescript
// Get busy times across all calendars
const { data: busyTimes, failedCalendars } = await recal.calendar.getBusyTimes('user_id', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z'
})
// Filter by provider
const { data: busyGoogle } = await recal.calendar.getBusyTimes('user_id', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
provider: 'google'
})
// Check multiple providers
const { data: busyAll } = await recal.calendar.getBusyTimes('user_id', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
provider: ['google', 'microsoft'],
timeZone: 'America/Los_Angeles'
})
```
**Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `provider` (optional): Filter by provider(s)
* `timeZone` (optional): Return results in specific timezone
**Response Format:**
Since 1.2.0 the method resolves to `{ data, failedCalendars }` rather than a bare array. `start` and
`end` come back as `Date` objects — the SDK converts the API's ISO 8601 strings for you.
```typescript
{
data: [
{
start: new Date('2024-01-15T10:00:00Z'),
end: new Date('2024-01-15T11:00:00Z')
},
{
start: new Date('2024-01-15T14:00:00Z'),
end: new Date('2024-01-15T15:30:00Z')
}
],
failedCalendars: [
{
calendarId: 'old-team@group.calendar.google.com',
provider: 'google',
reason: 'notFound',
message: 'The calendar does not exist or is no longer subscribed'
}
]
}
```
`failedCalendars` is always present, `[]` when every calendar was read. A non-empty list means
`data` covers only the calendars Recal could reach — see
[Troubleshooting](/core/troubleshooting#partial-results).
***
## Use Cases [#use-cases]
### Check User Availability [#check-user-availability]
```typescript
async function isUserAvailable(userId: string, start: string, end: string) {
const { data: busyTimes, failedCalendars } = await recal.calendar.getBusyTimes(userId, {
start,
end
})
// A calendar we could not read might hold the conflict, so fail closed
if (failedCalendars.length > 0) return false
// User is available if no busy times found
return busyTimes.length === 0
}
```
### Display User's Calendars [#display-users-calendars]
```typescript
async function displayCalendars(userId: string) {
const calendars = await recal.calendar.list(userId)
for (const calendar of calendars) {
console.log(`${calendar.name} (${calendar.provider})`)
console.log(` Timezone: ${calendar.timeZone}`)
console.log(` Access: ${calendar.accessRole}`)
}
}
```
### Aggregate Events Across Providers [#aggregate-events-across-providers]
```typescript
async function getAllUpcomingEvents(userId: string) {
const now = new Date()
const nextMonth = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000)
const events = await recal.calendar.listEvents(userId, {
start: now.toISOString(),
end: nextMonth.toISOString()
})
// Sort by start time
return events.sort((a, b) => a.start.getTime() - b.start.getTime())
}
```
***
## Best Practices [#best-practices]
1. **Use Appropriate Date Ranges**: Query only the time periods you need to minimize API load
2. **Filter by Provider**: If you only need one provider's data, filter to reduce response size
3. **Handle Timezones**: Always specify timezone when displaying times to users
4. **Cache Responses**: Calendar data doesn't change frequently - consider caching results
5. **Use Busy Times for Scheduling**: For scheduling, use `getBusyTimes()` instead of fetching full events
***
## Related [#related]
* See [Events](/sdk/javascript/events) for creating, updating, and deleting events
* See [Scheduling](/sdk/javascript/scheduling) for finding available time slots
* See [Organizations](/sdk/javascript/organizations) for team-wide availability queries
* See [Troubleshooting](/core/troubleshooting) for what to do about a non-empty `failedCalendars`
# Introduction
URL: /sdk/javascript
# Getting Started [#getting-started]
The Recal JavaScript SDK is an open-source software development kit for interacting with the Recal API using JavaScript and TypeScript. Build sophisticated calendar integrations with support for Google Calendar and Microsoft Outlook.
Security note: This SDK is designed for server-side use. Never expose your API token in client-side code.
***
## Features [#features]
* **Multi-Provider Support**: Seamlessly work with Google Calendar and Microsoft Outlook
* **Type Safety**: Full TypeScript support with runtime validation
* **Rich Calendar Operations**: Events, busy queries, scheduling, and more
* **Organization Management**: Handle organization and user calendars
* **OAuth Integration**: Built-in OAuth flow support for calendar connections
* **Error Handling**: Comprehensive error types for robust applications
* **Modern Architecture**: Clean, testable service-based design
***
## Setup [#setup]
### Create an Account & Get API Key [#create-an-account--get-api-key]
1. [Sign up](https://dash.recal.dev/sign-up) for a Recal account
2. Log in to your [Recal dashboard](https://dash.recal.dev)
3. Navigate to "API Keys" in the sidebar
4. Create a new API key and copy it to a secure location
### Set Up OAuth Providers [#set-up-oauth-providers]
1. Go to "OAuth Credentials" in the sidebar
2. Enter your OAuth Client ID and Secret
3. Save your credentials
To get the client ID and secret for each provider, follow the guides below:
* [Google OAuth Setup Guide](/core/oauth/google)
* [Microsoft OAuth Setup Guide](/core/oauth/microsoft)
### Install the SDK [#install-the-sdk]
Choose your preferred package manager to install the Recal SDK:
```bash
# npm
npm install recal-sdk
# bun
bun add recal-sdk
# yarn
yarn add recal-sdk
```
### Initialize the SDK [#initialize-the-sdk]
Import and initialize the SDK with your API key:
```typescript
import { Recal } from 'recal-sdk';
const recal = new Recal({
token: ""
});
```
You can also use environment variables:
```typescript
// Reads from process.env.RECAL_TOKEN
const recal = new Recal();
```
**Note:** `RecalClient` is available as an alias for backward compatibility, but `Recal` is the recommended import.
### Test Your Connection [#test-your-connection]
```typescript
import { Recal } from 'recal-sdk';
const recal = new Recal({
token: ""
});
const orgs = await recal.organizations.list();
console.log(orgs); // should log [] if you have no organizations
```
***
## Contribute to the SDK [#contribute-to-the-sdk]
The [Recal Node.js SDK](https://github.com/recal-dev/recal-sdk-js) repository contains the Node.js SDK. You can contribute to the SDK by creating an issue or opening a pull request.
***
# OAuth
URL: /sdk/javascript/oauth
## Understanding OAuth Operations [#understanding-oauth-operations]
The OAuth API manages secure connections between your users and their calendar providers (Google, Microsoft). It handles the complex authentication flows, token management, and permission scopes needed to access calendar data, providing a seamless integration experience for your application.
OAuth (Open Authorization) is the industry standard for secure API access. In calendar applications, OAuth enables:
**Secure Access**: Users grant your application permission to access their calendars without sharing passwords
**Token Management**: Automatic handling of access tokens, refresh tokens, and expiration cycles
***
## Prerequisites [#prerequisites]
Before implementing OAuth, ensure you have:
* Created a user using the [Users API](/sdk/javascript/users)
* Configured OAuth providers (Google, Microsoft) in your Recal dashboard
* Set up redirect URLs in both the OAuth provider's dashboard and Recal dashboard
## Understanding Tokens [#understanding-tokens]
OAuth uses two types of tokens to manage access:
### Access Tokens [#access-tokens]
* **Purpose**: Used to make API calls to access the user's calendar data
* **Lifespan**: Valid for 1 hour
* **Usage**: Include in API requests to authenticate and authorize calendar operations
### Refresh Tokens [#refresh-tokens]
* **Purpose**: Used to obtain new access tokens when they expire
* **Lifespan**: Valid for 30 days (varies by provider)
* **Usage**: Automatically handled by the system to maintain continuous access
**Important**: Access tokens expire frequently for security reasons. Refresh tokens allow your application to maintain access without requiring users to re-authenticate constantly.
***
## OAuth Flow Overview [#oauth-flow-overview]
The OAuth process consists of two main steps:
1. **Authorization**: Generate an OAuth link and redirect the user to the provider's authorization page
2. **Token Exchange**: Verify the authorization code and receive access/refresh tokens
**User → OAuth Link → Provider Authorization → Callback → Token Verification → Access Granted**
### Step 1: Generate OAuth Link [#step-1-generate-oauth-link]
#### Single Provider Link [#single-provider-link]
```typescript
// Get OAuth authorization URL (with defaults)
const link = await recal.oauth.getAuthLink(
'user_id',
'google'
)
console.log(link.url) // Use this URL to redirect user
// Or with custom options
const linkWithOptions = await recal.oauth.getAuthLink(
'user_id',
'google',
{
scope: 'write', // 'write', 'read', or 'free-busy'
accessType: 'offline', // 'offline' or 'online'
redirectUrl: 'https://app.example.com/callback' // optional
}
)
```
#### Multiple Provider Links [#multiple-provider-links]
```typescript
// Get OAuth URLs for all providers
const links = await recal.oauth.getAuthLinks('user_id')
console.log(links.google.url)
console.log(links.microsoft.url)
// Or with specific providers and options
const linksFiltered = await recal.oauth.getAuthLinks(
'user_id',
{
provider: ['google', 'microsoft'],
scope: 'write',
accessType: 'offline'
}
)
```
#### Configuration Options [#configuration-options]
**scope**: Determines the level of access your application requests
* `write`: Read/write access to events (create, modify, delete events). Also accepts deprecated `edit`.
* `read`: Read-only access to calendars and events
* `free-busy`: Read-only access to busy/free time information (no event details)
For detailed information on how scopes map to provider-specific permissions, see the [OAuth setup guide](/core/oauth).
**Upgrading Scopes**: If you need to add more scopes to your application (e.g., upgrading from `free-busy` to `write`), all existing users who authenticated with the previous scope level will need to re-authenticate. Their current OAuth connections will continue working but will only have access to the original scopes they granted. Plan scope requirements carefully before your initial launch to minimize user disruption.
**accessType**: Controls token types and session duration
* `offline`: Returns both access and refresh tokens (recommended for server applications). Connections remain active beyond the initial 30-minute access token expiration through automatic token refresh.
* `online`: Returns only access tokens (suitable for client-side applications). Sessions expire after 30 minutes.
**redirectUrl** *(optional)*:
* The URL where users are redirected after authorization
* Should be a callback endpoint/page in your application that can handle the authorization response code
* If not provided, uses the default redirect URL configured in your Recal dashboard
* Must match URLs configured in your OAuth provider's dashboard
* For local development, pass a different `redirectUrl` without changing your dashboard settings
### Step 2: Handle OAuth Callback [#step-2-handle-oauth-callback]
After the user completes authorization, they're redirected to your callback URL with query parameters:
* `code`: Authorization code to exchange for tokens
* `state`: Base64URL encoded string containing the user ID (for security)
* `scope`: Space-separated list of granted scopes from the provider
#### Verify Authorization Code [#verify-authorization-code]
```typescript
// Extract parameters from callback URL (frontend)
const urlParams = new URLSearchParams(window.location.search)
const code = urlParams.get('code')
const state = urlParams.get('state')
const scope = urlParams.get('scope')?.split(' ') || [] // Provider returns space-separated scopes
// Verify OAuth code from callback (backend)
const result = await recal.oauth.verifyCode(
'google',
{
code: code, // Authorization code from callback URL
state: state, // State parameter from callback URL
scope: scope // Array of granted scopes (required)
},
{
redirectUrl: 'https://app.example.com/callback' // Must match redirectUrl used in getAuthLink()
}
)
```
**Security Note**: Always verify the state parameter matches what you expect to prevent CSRF attacks.
***
## Managing OAuth Connections [#managing-oauth-connections]
Once established, OAuth connections can be managed through various operations:
### Retrieve Connections [#retrieve-connections]
Want to migrate from Recal to another system? We allow you to get the OAuth connections for a user so you can migrate without having to re-authenticate them.
```typescript
// Get all OAuth connections for a user (tokens hidden by default)
const connections = await recal.oauth.list('user_id')
// Get with full token details
const connectionsWithTokens = await recal.oauth.list('user_id', {
showToken: 'true'
})
// Get specific provider connection
const googleConnection = await recal.oauth.get('user_id', 'google')
// Get with full token details
const googleConnectionFull = await recal.oauth.get('user_id', 'google', {
showToken: 'true'
})
```
### Bring Your Own Tokens [#bring-your-own-tokens]
Migrating from another system to Recal? If you already have a user's refresh and access token, you can set them manually using the `create` method. This way, your users don't have to re-authenticate.
```typescript
// Set OAuth tokens manually (useful for migrations or testing)
const connection = await recal.oauth.create(
'user_id',
'google',
{
accessToken: 'access_token_here',
refreshToken: 'refresh_token_here', // optional but recommended
scope: ['calendar.events', 'calendar.readonly'],
expiresAt: new Date('2024-12-31'), // optional
email: 'user@example.com' // optional
}
)
```
### Disconnect Provider [#disconnect-provider]
```typescript
// Remove OAuth connection for a provider
await recal.oauth.delete('user_id', 'google')
```
***
## Get a Fresh Access Token [#get-a-fresh-access-token]
Recal handles all the token refresh logic for you, but in some cases, you might want to get a fresh access token for a user.
For example, you might be using Recal to integrate calendars into your product, but you also want to integrate with other services like Google Drive or Outlook Mail.
In order to make calls to other Google services, you need to get a fresh access token for the user. You can do this by calling the `getFreshAccessToken` method.
To integrate with other Google services, you need to make sure your OAuth provider app is configured to have the required scopes.
```typescript
// Get a fresh access token for a user for a specific provider
const tokenData = await recal.oauth.getFreshAccessToken('user_id', 'google')
console.log(tokenData.accessToken)
console.log(tokenData.expiresAt)
// Use this token for other Google/Microsoft services
```
***
## Best Practices [#best-practices]
1. **Use Offline Access**: Always request `accessType: 'offline'` for server-side applications. This provides refresh tokens that keep connections active beyond the 30-minute access token expiration through automatic renewal with a refresh token.
2. **Request Minimum Scope**: Only request the scope you need (`free-busy` \< `read` \< `write`)
3. **Verify State Parameter**: Always validate the state parameter in callbacks to prevent CSRF attacks
4. **Handle Expiration**: Recal automatically refreshes tokens, but be prepared to handle re-authentication flows
5. **Secure Token Storage**: Never expose full tokens in client-side code - avoid using `showToken: 'true'` in production
6. **Match Redirect URLs**: Ensure redirect URLs match exactly between OAuth provider dashboard, Recal dashboard, and your code
7. **Test Both Providers**: Google and Microsoft have slightly different OAuth behaviors - test both thoroughly
***
## Related [#related]
* See [Error Handling](/sdk/javascript/error-handling) for handling SDK errors
* See [Users](/sdk/javascript/users) for managing users
* See [Events](/sdk/javascript/events) for working with calendar events
# Organizations
URL: /sdk/javascript/organizations
## Understanding Organizations [#understanding-organizations]
Organizations in Recal serve as containers for managing users and their calendar integrations. This hierarchical structure enables two primary use cases:
### Multi-Tenant B2B Applications [#multi-tenant-b2b-applications]
Create separate organizations for each of your business customers. For example, if you provide scheduling software for different companies, each company gets its own organization with isolated user management.
### Direct-to-Consumer B2C Applications [#direct-to-consumer-b2c-applications]
Skip organizations entirely and manage all individual users directly under your main organization. Perfect for consumer calendar apps where users don't need to be grouped by company.
***
## Organization Management [#organization-management]
### Get Organization [#get-organization]
```typescript
// Get organization by slug
const org = await recal.organizations.get('acme-corp')
```
### List All Organizations [#list-all-organizations]
```typescript
// Get all organizations in your account
const orgs = await recal.organizations.list()
// Get all organizations for a specific user
const userOrgs = await recal.users.getOrganizations('user_id')
```
### Create Organization [#create-organization]
```typescript
// Create a new organization
const org = await recal.organizations.create(
'acme-corp', // slug
'Acme Corporation' // name
)
```
**Note:** Slugs must be unique and lowercase. It's recommended to match your internal database IDs for easier usage.
### Update Organization [#update-organization]
```typescript
// Update organization
const updated = await recal.organizations.update('acme-corp', {
slug: 'new-slug',
name: 'New Name'
})
```
### Delete Organization [#delete-organization]
```typescript
// Delete an organization and remove all member associations
await recal.organizations.delete('acme-corp')
```
## Member Management [#member-management]
Organizations can have multiple members. Members are users assigned to an organization, enabling shared calendar operations and team scheduling.
### Get Members [#get-members]
```typescript
// Get all members of an organization
const members = await recal.organizations.getMembers('acme-corp')
```
### Add Members [#add-members]
```typescript
// Add users to an organization
await recal.organizations.addMembers(
'acme-corp',
['user_id_1', 'user_id_2']
)
```
### Remove Members [#remove-members]
```typescript
// Remove users from an organization
await recal.organizations.removeMembers(
'acme-corp',
['user_id_1', 'user_id_2']
)
```
***
## Organization-Wide Availability [#organization-wide-availability]
Organizations support team-wide availability queries for coordinating across multiple members.
### Get Organization Busy Times [#get-organization-busy-times]
```typescript
// Get consolidated busy times for all organization members
const { data: orgBusy, failedUsers } = await recal.organizations.getBusyTimes('acme-corp', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z'
})
// With provider filter
const { data: orgBusyGoogle } = await recal.organizations.getBusyTimes('acme-corp', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
provider: ['google']
})
```
### Find Team Availability Slots [#find-team-availability-slots]
```typescript
// Find times when the entire organization is available
const { data: slots, failedUsers } = await recal.organizations.getScheduling('acme-corp', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-19T23:59:59Z',
slotDuration: '60', // 60 minutes
padding: '15' // 15 minutes padding between meetings
})
// With additional constraints
const { data: constrainedSlots } = await recal.organizations.getScheduling('acme-corp', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-19T23:59:59Z',
slotDuration: '30',
padding: '10',
earliestTimeEachDay: '09:00',
latestTimeEachDay: '17:00',
provider: ['google', 'microsoft'],
timeZone: 'America/New_York'
})
```
Since 1.2.0 both methods resolve to `{ data, failedUsers }`. A non-empty `failedUsers` means `data`
is partial: each entry names a member by `customId` with a `reason`, and an empty `failedCalendars`
on that entry means nothing of theirs was readable at all. Members with no connected calendar are
not listed — [what to do](/core/troubleshooting).
**Use Cases:**
* Team meeting scheduling
* Department-wide availability
* Cross-team coordination
* Resource allocation
***
## Best Practices [#best-practices]
1. **Unique Slugs**: Use lowercase, URL-safe slugs that match your internal database IDs
2. **Member Management**: Add users to organizations before querying their calendar data
3. **Team Queries**: Use organization-level methods for multi-user availability checks
4. **Hierarchy**: Structure organizations to match your business model (B2B vs B2C)
5. **Cleanup**: Remove members before deleting organizations to maintain data integrity
# Scheduling
URL: /sdk/javascript/scheduling
## Understanding Scheduling [#understanding-scheduling]
The Scheduling API is your intelligent assistant for finding optimal meeting times and managing availability across users and organizations.
It analyzes calendar data, applies business rules, and returns ready-to-book time slots, eliminating the back-and-forth of manual scheduling coordination.
### Key Concepts [#key-concepts]
**Smart Slot Generation**: Automatically finds available time periods based on calendar data, working hours, and your preferences.
**Multi-Calendar Awareness**: Considers calendars across all connected providers (Google, Microsoft, etc.) to prevent conflicts and double-booking.
**Business Rules Integration**: Applies working hours, padding between meetings, and custom schedules to match real-world constraints.
**Team Coordination**: Finds times when multiple people or entire organizations are available simultaneously.
**Timezone Intelligence**: Handles timezone conversions and displays results in the appropriate timezone for each participant.
***
## Single User Scheduling [#single-user-scheduling]
### Basic User Availability [#basic-user-availability]
Find available time slots for a single user with simple constraints.
```typescript
// Find available time slots (minimal config)
const slots = await recal.scheduling.getSlots('user_id', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
slotDuration: '30' // Only required: slot duration in minutes
})
// Or with more options
const detailedSlots = await recal.scheduling.getSlots('user_id', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
slotDuration: '30', // Duration of each slot in minutes
padding: '10', // Padding between slots (minutes)
maxOverlaps: '0', // Only completely free slots
earliestTimeEachDay: '09:00', // Format: HH:mm
latestTimeEachDay: '17:00', // Format: HH:mm
provider: 'google', // optional: filter by provider
timeZone: 'America/New_York' // optional
})
```
**Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `slotDuration` (required): Duration of each slot in minutes (as string)
* `padding` (optional): Minutes between meetings (as string, default: `'0'`)
* `maxOverlaps` (optional): Allow slots with up to N overlapping events (as string, default: `'0'`)
* `earliestTimeEachDay` (optional): Start of working hours (HH:mm format)
* `latestTimeEachDay` (optional): End of working hours (HH:mm format)
* `provider` (optional): Filter by `'google'` or `'microsoft'`
* `timeZone` (optional): Timezone for results
### Advanced User Availability [#advanced-user-availability]
For more complex scheduling requirements with custom work schedules per day and advanced parameters.
```typescript
// Define custom schedules
const slots = await recal.scheduling.getAdvancedSlots(
'user_id',
{
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
slotDuration: '60',
padding: '15',
maxOverlaps: '1' // Allow up to 1 overlapping event
},
{
schedules: [
{
days: ['monday', 'wednesday', 'friday'],
start: '09:00',
end: '17:00'
},
{
days: ['tuesday', 'thursday'],
start: '10:00',
end: '16:00'
}
]
}
)
```
**Query Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `slotDuration` (required): Duration of each slot in minutes (as string)
* `padding` (optional): Minutes between meetings (as string, default: `'0'`)
* `maxOverlaps` (optional): Allow slots with up to N overlapping events (as string, default: `'0'`)
* `provider` (optional): Filter by `'google'` or `'microsoft'`
* `timeZone` (optional): Timezone for results
**Schedule Options:**
* `days`: Array of day names (`'monday'`, `'tuesday'`, `'wednesday'`, `'thursday'`, `'friday'`, `'saturday'`, `'sunday'`)
* `start`: Working hours start time (HH:mm format)
* `end`: Working hours end time (HH:mm format)
**Note:** The `maxOverlaps` parameter is useful for scenarios where some event conflicts are acceptable (e.g., optional meetings, tentative events). When set to `0` (default), only completely free slots are returned.
***
## Multi-User Scheduling [#multi-user-scheduling]
Find available time slots for multiple users independently. This endpoint processes each user separately and returns individual availability results.
**Important:** This is NOT a "find common availability" endpoint. Each user's available slots are calculated independently based on their own calendars and schedules. If you need to find times when ALL users are available simultaneously, you'll need to intersect the results yourself.
**Need a built-in common availability finder or other scheduling features?** If you think a native "find common slots" feature or any other scheduling functionality would be useful for your use case, we'd love to hear from you! Please reach out to [hello@recal.dev](mailto:hello@recal.dev) and explain your specific requirements.
```typescript
// Basic multi-user availability
const results = await recal.scheduling.getMultiUserSlots(
{
start: '2024-01-15T00:00:00Z',
end: '2024-01-19T23:59:59Z',
slotDuration: '60'
},
{
users: [
{ id: 'user_1' },
{ id: 'user_2' },
{ id: 'user_3' }
]
}
)
// With custom schedules and calendars per user
const advancedResults = await recal.scheduling.getMultiUserSlots(
{
start: '2024-01-15T00:00:00Z',
end: '2024-01-19T23:59:59Z',
slotDuration: '60',
padding: '15',
maxOverlaps: '1', // Allow up to 1 overlapping event per user
provider: 'google', // Filter to specific provider
timeZone: 'America/New_York'
},
{
users: [
{
id: 'user_1',
calendarIds: ['primary', 'work@company.com'], // Specific calendars
schedules: [
{
days: ['monday', 'wednesday', 'friday'],
start: '09:00',
end: '17:00'
}
]
},
{
id: 'user_2',
schedules: [
{
days: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
start: '10:00',
end: '16:00'
}
]
},
{ id: 'user_3' } // Uses default constraints
]
}
)
```
**Query Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `slotDuration` (required): Duration of each slot in minutes (as string)
* `padding` (optional): Minutes between meetings (as string, default: `'0'`)
* `maxOverlaps` (optional): Allow slots with up to N overlapping events (as string, default: `'0'`)
* `provider` (optional): Filter by `'google'` or `'microsoft'`
* `timeZone` (optional): Timezone for results
**User Configuration:**
* `id` (required): User ID
* `calendarIds` (optional): Calendar ID, or array of IDs, to check (defaults to `['primary']`)
* `schedules` (optional): Array of custom schedule rules for this user
**Response Format:**
The endpoint returns an array with one entry per user. Users are resolved independently, so
one user failing never fails the request — each entry is discriminated by `status`.
**Success Response (`status: 'ok'`):**
```typescript
{
userId: string, // The user ID you provided
status: 'ok',
availableSlots: Array<{ // Available time slots for this user
start: Date, // Date object, converted from ISO 8601
end: Date
}>,
options: { // The scheduling parameters used
padding: number,
slotDuration: number,
start: Date,
end: Date,
schedules?: Array<...>,
maxOverlaps: number,
calendarIds?: string | string[]
},
failedCalendars: Array<{ // Since 1.2.0 — always present, [] when nothing failed
calendarId: string,
provider: 'google' | 'microsoft',
reason: FreeBusyFailureReason,
message: string
}>
}
```
**Error Response (`status: 'error'`):**
```typescript
{
userId: string, // The user ID you provided
status: 'error',
error: string, // Error message (e.g., "User not found", "User has no connected calendars")
reason?: FreeBusyFailureReason // Since 1.2.0 — present only when a calendar provider failed
}
```
The two provisioning messages — `"User not found"` and `"User has no connected calendars"` — carry
no `reason`; they are states you control rather than failures. Every other `error` entry carries one,
and its `error` text is that reason's fixed message. See
[Troubleshooting](/core/troubleshooting#reason-reference) for the ten codes.
Slots are computed from the busy time Recal could read, so a calendar it could not read cannot
narrow them. If the conflict lived on that calendar, the slot still looks open — availability errs
**wide**, never narrow. Decide per request whether to book, confirm out of band, or withhold:
[what a missing calendar does to availability](/core/troubleshooting#what-a-missing-calendar-does-to-availability).
With `maxOverlaps` above `0`, a calendar that cannot be read fails that user's whole entry rather
than trimming it — you get a `status: 'error'` entry instead of an `ok` one with `failedCalendars`.
Changing only `maxOverlaps` therefore changes which entry kind a bad calendar produces.
Check `status` before reading `availableSlots` — it is absent on failed entries. An entry never
reports an empty `availableSlots` to mean failure — but check `failedCalendars` too: `[]` means no
availability *among the calendars that could be read*.
**Example Response:**
```typescript
[
{
userId: 'user_1',
status: 'ok',
availableSlots: [
{ start: '2024-01-15T09:00:00Z', end: '2024-01-15T10:00:00Z' },
{ start: '2024-01-15T14:00:00Z', end: '2024-01-15T15:00:00Z' }
],
options: {
padding: 15,
slotDuration: 60,
start: '2024-01-15T00:00:00.000Z',
end: '2024-01-19T23:59:59.000Z',
maxOverlaps: 0
},
failedCalendars: []
},
{
userId: 'user_2',
status: 'ok',
availableSlots: [
{ start: '2024-01-15T10:00:00Z', end: '2024-01-15T11:00:00Z' }
],
options: { /* ... */ },
failedCalendars: [
{
calendarId: 'old-team@group.calendar.google.com',
provider: 'google',
reason: 'notFound',
message: 'The calendar does not exist or is no longer subscribed'
}
]
},
{
userId: 'user_3',
status: 'error',
error: 'User has no connected calendars'
},
{
userId: 'user_4',
status: 'error',
error: 'The stored calendar authorization is no longer valid',
reason: 'authorizationInvalid'
}
]
```
**Key Behaviors:**
* Each user is processed independently and concurrently
* If one user fails, others still succeed (error isolation)
* Users without OAuth connections return an error response
* Non-existent users return "User not found" error
* Empty `availableSlots` with empty `failedCalendars` means the user is completely booked; with a non-empty `failedCalendars` it means booked among what could be read
**Use Cases:**
* Displaying individual availability for multiple team members
* Building a team scheduling UI showing each person's free slots
* Batch processing availability checks
* Comparing schedules across team members
***
## Organization-Wide Scheduling [#organization-wide-scheduling]
For team-wide availability, you can also use organization-level scheduling methods:
```typescript
// Find organization-wide available time slots
const { data: orgSlots, failedUsers } = await recal.organizations.getScheduling('org-slug', {
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
slotDuration: '60',
padding: '15',
maxOverlaps: '0', // Only completely free slots
earliestTimeEachDay: '09:00',
latestTimeEachDay: '17:00',
provider: ['google', 'microsoft'],
timeZone: 'America/New_York'
})
```
**Parameters:**
* `start` (required): ISO 8601 timestamp for range start
* `end` (required): ISO 8601 timestamp for range end
* `slotDuration` (required): Duration of each slot in minutes (as string)
* `padding` (optional): Minutes between meetings (as string, default: `'0'`)
* `maxOverlaps` (optional): Allow slots with up to N overlapping events (as string, default: `'0'`)
* `earliestTimeEachDay` (optional): Start of working hours (HH:mm format)
* `latestTimeEachDay` (optional): End of working hours (HH:mm format)
* `provider` (optional): Filter by provider(s)
* `timeZone` (optional): Timezone for results
Since 1.2.0 this method resolves to `{ data, failedUsers }`. A non-empty `failedUsers` means the
slots were computed without those members' calendars — see
[Troubleshooting](/core/troubleshooting#partial-results).
See [Organizations](/sdk/javascript/organizations) for more details on team scheduling.
***
## Response Format [#response-format]
### Single User Methods [#single-user-methods]
Both `getSlots()` and `getAdvancedSlots()` return an object with available slots and the options used:
```typescript
{
availableSlots: [
{
start: '2024-01-15T10:00:00Z',
end: '2024-01-15T10:30:00Z'
},
{
start: '2024-01-15T14:00:00Z',
end: '2024-01-15T14:30:00Z'
},
{
start: '2024-01-16T09:00:00Z',
end: '2024-01-16T09:30:00Z'
}
],
options: {
padding: 15,
slotDuration: 30,
start: '2024-01-15T00:00:00.000Z',
end: '2024-01-20T23:59:59.000Z',
maxOverlaps: 0
}
}
```
### Multi-User Methods [#multi-user-methods]
`getMultiUserSlots()` returns an array with one entry per user - see the detailed response format in the [Multi-User Scheduling](#multi-user-scheduling) section above.
***
## Use Cases [#use-cases]
### Simple Booking System [#simple-booking-system]
```typescript
async function findNextAvailableSlot(userId: string) {
const now = new Date()
const oneWeekLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
const result = await recal.scheduling.getSlots(userId, {
start: now.toISOString(),
end: oneWeekLater.toISOString(),
slotDuration: '30',
padding: '10',
earliestTimeEachDay: '09:00',
latestTimeEachDay: '17:00'
})
return result.availableSlots[0] // Return first available slot
}
```
### Team Availability Dashboard [#team-availability-dashboard]
```typescript
async function getTeamAvailability(userIds: string[]) {
const startDate = new Date()
const endDate = new Date(startDate.getTime() + 14 * 24 * 60 * 60 * 1000)
const results = await recal.scheduling.getMultiUserSlots(
{
start: startDate.toISOString(),
end: endDate.toISOString(),
slotDuration: '60',
padding: '15'
},
{
users: userIds.map(id => ({ id }))
}
)
// Process results for each user
return results.map(result => {
if ('error' in result) {
return {
userId: result.userId,
error: result.error,
slots: []
}
}
return {
userId: result.userId,
slots: result.availableSlots.slice(0, 5) // First 5 slots per user
}
})
}
// Find common availability across all users
async function findCommonAvailability(userIds: string[]) {
const startDate = new Date()
const endDate = new Date(startDate.getTime() + 7 * 24 * 60 * 60 * 1000)
const results = await recal.scheduling.getMultiUserSlots(
{
start: startDate.toISOString(),
end: endDate.toISOString(),
slotDuration: '60',
padding: '15'
},
{
users: userIds.map(id => ({ id }))
}
)
// Filter out errors and get only successful results
const successResults = results.filter(r => 'availableSlots' in r)
if (successResults.length === 0) {
return []
}
// Find slots that appear in ALL users' availability
const firstUserSlots = successResults[0].availableSlots
return firstUserSlots.filter(slot =>
successResults.every(result =>
result.availableSlots.some(s =>
s.start === slot.start && s.end === slot.end
)
)
)
}
```
### Custom Work Schedule [#custom-work-schedule]
```typescript
async function findSlotsWithFlexibleHours(userId: string) {
const result = await recal.scheduling.getAdvancedSlots(
userId,
{
start: '2024-01-15T00:00:00Z',
end: '2024-01-20T23:59:59Z',
slotDuration: '45',
padding: '15'
},
{
schedules: [
{
days: ['monday', 'wednesday', 'friday'],
start: '08:00',
end: '12:00'
},
{
days: ['tuesday', 'thursday'],
start: '13:00',
end: '18:00'
}
]
}
)
return result.availableSlots
}
```
***
## Best Practices [#best-practices]
1. **Appropriate Date Ranges**: Query 1-2 weeks at a time for optimal performance
2. **Reasonable Slot Durations**: Use 15, 30, or 60-minute slots for best results
3. **Include Padding**: Add 5-15 minutes between meetings for buffer time
4. **Set Working Hours**: Use `earliestTimeEachDay` and `latestTimeEachDay` to respect work-life balance
5. **Timezone Awareness**: Always specify timezone when displaying slots to users
6. **Cache Results**: Slot availability is relatively stable - cache for 5-15 minutes
7. **Limit User Count**: For multi-user scheduling, optimal performance with 2-10 users
8. **Use Custom Schedules**: For complex availability patterns, use `getAdvancedSlots()` or per-user schedules
***
## Related [#related]
* See [Calendar & Availability](/sdk/javascript/free-busy) for busy time queries
* See [Organizations](/sdk/javascript/organizations) for team-wide scheduling
* See [Events](/sdk/javascript/events) for booking the scheduled slots
* See [Troubleshooting](/core/troubleshooting) for partial answers and what each `reason` means
# Types
URL: /sdk/javascript/types
All types returned by the Recal SDK are fully typed for TypeScript. Below are the core types you'll work with.
***
## User [#user]
The user entity represents a person who can connect their calendars to Recal.
**Key Features:**
* **Custom IDs**: Map to your database (e.g., `user_${yourDbId}`)
* **Multi-Org Support**: Users can belong to multiple organizations
* **OAuth Connections**: Users connect Google, Microsoft calendars
***
## Organization [#organization]
Organizations group users together for B2B multi-tenancy or team collaboration.
**Key Features:**
* **Unique Slug**: Custom identifier for your database mapping
* **Team Management**: Add/remove members dynamically
* **Data Isolation**: Each organization's data is completely separate
***
## OAuth Connection [#oauth-connection]
OAuth connections represent a user's authenticated link to a calendar provider.
**Key Features:**
* **Provider Support**: Google Calendar, Microsoft Outlook
* **Token Management**: Automatic refresh token handling
* **Scope Control**: `write` (event access), `read` (read-only), or `free-busy` (availability only)
* **Status Tracking**: `alive` field indicates connection health
***
## Event [#event]
Calendar events unified across all providers.
**Key Features:**
* **Unified Format**: Same structure regardless of provider
* **Meta ID**: Optional custom identifier for your database
* **Attendees**: Email-based participant tracking
* **Meeting Links**: Automatic Google Meet/Teams integration
* **ISO Timestamps**: All dates in ISO 8601 format
***
## Attendee [#attendee]
Represents a participant in a calendar event.
***
## Calendar [#calendar]
Represents a calendar from a connected provider.
***
## CreateEvent [#createevent]
Payload for creating a new event.
***
## UpdateEvent [#updateevent]
Payload for updating an existing event. All fields are optional.
***
## TimeRange [#timerange]
Represents a time range with start and end timestamps.
***
## Enums and Unions [#enums-and-unions]
### Provider [#provider]
Calendar provider types supported by Recal.
```typescript
type Provider = 'google' | 'microsoft'
```
### CalendarAccessRole [#calendaraccessrole]
User's access level for a calendar.
```typescript
type CalendarAccessRole = 'owner' | 'writer' | 'reader' | 'freeBusyReader'
```
* **owner**: Full control over the calendar
* **writer**: Can create and modify events
* **reader**: Read-only access to events
* **freeBusyReader**: Can only see free/busy information
### DayOfWeek [#dayofweek]
Days of the week for scheduling.
```typescript
type DayOfWeek =
| 'monday'
| 'tuesday'
| 'wednesday'
| 'thursday'
| 'friday'
| 'saturday'
| 'sunday'
```
### OAuthAccessType [#oauthaccesstype]
OAuth access type for token management.
```typescript
type OAuthAccessType = 'online' | 'offline'
```
* **offline**: Returns both access and refresh tokens (recommended for server apps)
* **online**: Returns only access tokens
### OAuthScope [#oauthscope]
OAuth permission scopes for calendar access.
```typescript
type OAuthScope = 'write' | 'edit' | 'read' | 'free-busy'
```
* **write**: Read/write access to events. `edit` is deprecated — accepted as a synonym, to be removed
* **read**: Read-only access to calendars and events
* **free-busy**: Read-only access to availability information
### AttendeeResponseStatus [#attendeeresponsestatus]
Attendee response status for event invitations.
```typescript
type AttendeeResponseStatus =
| 'needsAction' // No response yet
| 'accepted' // Accepted invitation
| 'tentative' // Maybe attending
| 'declined' // Declined invitation
```
## Usage Example [#usage-example]
```typescript
import { Recal, type CreateEvent, type Provider } from 'recal-sdk'
const recal = new Recal({ token: process.env.RECAL_TOKEN })
const eventData: CreateEvent = {
subject: 'Team Meeting',
start: '2024-01-15T10:00:00Z',
end: '2024-01-15T11:00:00Z',
attendees: [
{ email: 'team@example.com' }
],
meeting: true
}
const provider: Provider = 'google'
const event = await recal.events.createEvent(
'user_123',
provider,
'primary',
eventData
)
```
## Next Steps [#next-steps]
# Users
URL: /sdk/javascript/users
## Understanding Users [#understanding-users]
Users represent individual people in your calendar system.
They are the core entities that connect calendar accounts (Google Calendar, Microsoft Outlook) to Recal, enabling calendar access and event management.
They can exist independently (User) or be associated with one or more organizations (Member).
**Key Concepts:**
* Users have a custom string ID that you control (recommended to match your database)
* One user can connect multiple calendar providers simultaneously
* Users can be members of multiple organizations
* All calendar operations are performed in the context of a specific User
## User Management [#user-management]
### Get User [#get-user]
```typescript
// Get user information (basic)
const user = await recal.users.get('user_id')
// Or with additional data
const userWithDetails = await recal.users.get('user_id', {
include: ['organizations', 'oauthConnections']
})
```
### List All Users [#list-all-users]
```typescript
// Get all users in your organization
const users = await recal.users.list()
```
### Get User's Organizations [#get-users-organizations]
```typescript
// Get all organizations a user belongs to
const organizations = await recal.users.getOrganizations('user_id')
```
### Create User [#create-user]
```typescript
// Create a new user (without organizations)
const user = await recal.users.create('user_id')
// Or with organization memberships
const userWithOrgs = await recal.users.create(
'user_id',
['org-slug-1', 'org-slug-2'] // optional: organization slugs
)
```
### Update User [#update-user]
```typescript
// Update user ID
const updatedUser = await recal.users.update('old_user_id', 'new_user_id')
```
### Delete User [#delete-user]
```typescript
// Deletes user from all organizations and removes associated OAuth connections
await recal.users.delete('user_id')
```