Back to Blog
Laptop displaying code with colorful lighting
Tutorial
8 min read

Supabase Calendar: Build a Calendar App With JavaScript

By SimpleCalendarJS Team

SimpleCalendarJS~14 KB gzipped · Zero dependencies · Any framework
Short answer

To build a Supabase calendar, store events in a Postgres table with timestamptz start and end columns, protect it with Row Level Security, and query it from the browser with supabase-js. Load only events that overlap the visible range (start before the range end, end after the range start), then subscribe to Realtime changes so the calendar refreshes itself.

A Supabase calendar is a common thing to build: you want users to see, add and move events, and you'd rather not write and host an API just to store them. Supabase gives you a hosted Postgres database, authentication and realtime updates. Pair it with a front-end calendar component and you can have a working multi-user calendar app with a few SQL statements and one JavaScript file.

This tutorial covers the full path: a schema that suits calendar queries, Row Level Security so users only see their own events, a date-range query that loads only what's on screen, saving drag-and-drop changes, and live updates through Supabase Realtime.

Why Supabase Works for a Calendar Backend

Calendar data is simple, but the backend has to get a few things right:

  • Range queries. A calendar only shows one month, week or day at a time, so you need fast "events between X and Y" queries. Postgres handles this well with an index on the time columns.
  • Per-user access. Every user should see their own events (or their team's). Supabase handles this with Row Level Security (RLS) policies inside the database, so the browser can query the table directly with a public key.
  • Time zones. Postgres timestamptz stores every value as a UTC instant, which is what you want for events seen by users in different zones.
  • Live updates. When a colleague moves a meeting, your view should change too. Supabase Realtime can push database changes to subscribed clients.

You do the frontend work: render a month/week/day grid, request the right date range, and send creates, moves and deletes back to the database. If you've already loaded events from your own API, the pattern is the same as in loading calendar events from a REST API. Supabase just replaces the fetch call.

Designing the Events Table

Create the table in the Supabase SQL editor. Keep the columns close to what a calendar needs:

create table public.events ( id bigint generated always as identity primary key, user_id uuid not null default auth.uid() references auth.users (id) on delete cascade, title text not null, description text, start_at timestamptz not null, end_at timestamptz not null, all_day boolean not null default false, color text, created_at timestamptz not null default now(), constraint events_end_not_before_start check (end_at >= start_at) ); -- RLS filters on user_id, so index it create index events_user_id_idx on public.events using btree (user_id); -- Range queries filter on start_at and end_at create index events_user_range_idx on public.events (user_id, start_at, end_at);

A few deliberate choices:

  1. timestamptz, not timestamp. The PostgreSQL docs say values are "stored internally as UTC" and converted back with an offset on output. The browser gets an ISO string with an offset that new Date() parses to the exact instant.
  2. user_id defaults to auth.uid(). The client never sends a user ID, so it can't send someone else's. The database fills it in from the signed-in session.
  3. A check constraint rejects events that end before they start, whichever client caused it.
  4. Separate start_at and end_at columns instead of a range type. They map straight to a calendar event's start and end, and the overlap query below stays readable.

Locking It Down With Row Level Security

The browser will query this table with your project's publishable key. Supabase's API keys docs describe the publishable key (sb_publishable_...) as safe for web pages because it can only reach what your RLS policies allow. The secret key (sb_secret_...) bypasses RLS and must never reach the browser. (The docs also say the legacy anon and service_role JWT keys are deprecated and planned for retirement by the end of 2026, so use publishable keys in new projects.)

With RLS enabled and no policies, nobody can read anything. Add one policy per operation, following the pattern in the Supabase RLS guide:

alter table public.events enable row level security; create policy "Users can view their own events" on public.events for select to authenticated using ( (select auth.uid()) = user_id ); create policy "Users can create their own events" on public.events for insert to authenticated with check ( (select auth.uid()) = user_id ); create policy "Users can update their own events" on public.events for update to authenticated using ( (select auth.uid()) = user_id ) with check ( (select auth.uid()) = user_id ); create policy "Users can delete their own events" on public.events for delete to authenticated using ( (select auth.uid()) = user_id );

Some details from the docs are worth knowing:

  • Wrap auth.uid() in a select. Postgres then evaluates it once per statement, not once per row.
  • UPDATE needs a SELECT policy. Without the select policy, updates don't behave as expected, so keep both.
  • auth.uid() is null for signed-out requests. The comparison is then false and access is denied. That's what you want, but it also means a signed-out user sees an empty calendar instead of an error.

For a shared team calendar, keep the same structure but swap the condition for a membership check (for example, a team_id column and an exists (...) subquery on a team_members table).

Need a calendar in your app?

SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.

Querying Supabase Calendar Events by Date Range

The most common bug in calendar backends is loading events by start date only. An event that starts on 30 June and ends on 2 July belongs in the July view, but start_at >= July 1 misses it.

The correct test is an overlap: an event is visible if it starts before the range ends and ends after the range starts. With supabase-js filters, that's one lt and one gt:

const { data, error } = await supabase .from('events') .select('id, title, description, start_at, end_at, all_day, color') .lt('start_at', rangeEnd.toISOString()) .gt('end_at', rangeStart.toISOString());

There's no user_id filter in the query. RLS adds it on the server, so a user can't get around it by editing the query in DevTools. The composite index on (user_id, start_at, end_at) keeps the policy plus the range filter fast as the table grows.

Note that .toISOString() sends UTC, and Postgres compares instants, so the user's time zone doesn't affect the result.

Building the Supabase Calendar With SimpleCalendarJS

Now the frontend. SimpleCalendarJS is a zero-dependency calendar component (about 14 KB gzipped JS, 19 KB with the CSS) with month, week, day and list views. It fits this setup well: events are loaded through a single async function, fetchEvents(start, end), which it calls with the visible date range. That lines up exactly with the overlap query above.

Install both packages:

npm install @supabase/supabase-js simple-calendar-js

Give the container an inline height, so month view stays a fixed size and shows "+N more" on busy days:

<div id="calendar" style="height: 640px"></div> <script type="module" src="/main.js"></script>

Here's the full main.js. It loads events, creates one when a user clicks an empty slot, deletes one on click, and saves drag-and-drop and resize changes:

import { createClient } from '@supabase/supabase-js'; import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; const supabase = createClient( 'https://your-project.supabase.co', 'sb_publishable_your_key' ); // Map a database row to a calendar event function toCalendarEvent(row) { return { id: row.id, title: row.title, start: new Date(row.start_at), end: new Date(row.end_at), allDay: row.all_day, color: row.color || '#4f46e5', description: row.description || '' }; } // Called by the calendar with the visible date range async function fetchEvents(start, end) { const { data, error } = await supabase .from('events') .select('id, title, description, start_at, end_at, all_day, color') .lt('start_at', end.toISOString()) .gt('end_at', start.toISOString()); if (error) { console.error('Failed to load events', error); return []; } return data.map(toCalendarEvent); } let currentView = 'week'; const calendar = new SimpleCalendarJs('#calendar', { defaultView: 'week', enabledViews: ['month', 'week', 'day', 'list'], weekStartsOn: 1, enableDragDrop: true, enableResize: true, autoContrastText: true, allowHtmlInEvents: false, // titles are user input: render as plain text fetchEvents, onViewChange: (view) => { currentView = view; }, // Click an empty slot: create a one-hour event onSlotClick: async (date) => { const title = window.prompt('Event title'); if (!title) return; const start = new Date(date); if (currentView === 'month') start.setHours(9, 0, 0, 0); const end = new Date(start.getTime() + 60 * 60 * 1000); const { error } = await supabase.from('events').insert({ title, start_at: start.toISOString(), end_at: end.toISOString() }); if (error) { alert(`Could not create event: ${error.message}`); return; } calendar.refresh(); }, // Click an event: delete it after confirmation onEventClick: async (event) => { if (!window.confirm(`Delete "${event.title}"?`)) return; const { error } = await supabase .from('events') .delete() .eq('id', event.id); if (error) alert(`Could not delete event: ${error.message}`); calendar.refresh(); }, // Drag or resize: save the new times onEventDrop: async (event, oldStart, oldEnd, newStart, newEnd) => { const { data, error } = await supabase .from('events') .update({ start_at: newStart.toISOString(), end_at: newEnd.toISOString() }) .eq('id', event.id) .select('id'); if (error || data.length === 0) { alert('Could not save the change. Reverting.'); } // Reload from the database either way, so the UI matches what was saved calendar.refresh(); } });

How the pieces connect:

  • fetchEvents is the only read path. SimpleCalendarJS caches results per month grid, so going back and forth between weeks of the same month doesn't hit Supabase again.
  • refresh() after every write. It clears that cache and calls fetchEvents again, so the calendar shows exactly what the database accepted, including defaults and constraint rejections. There's no client-side addEvent to keep in sync.
  • The update chains .select('id'). By default supabase-js doesn't return updated rows. Asking for them lets you tell when RLS matched no rows (the user doesn't own the event) and the move didn't happen.
  • No user_id anywhere in the client. The column default and the RLS policies take care of it.

The prompt and confirm calls stand in for real UI. SimpleCalendarJS has no built-in event forms, so in a real app you'd open your own modal from onSlotClick and onEventClick, with title, description, color and an all-day toggle. The Supabase calls stay the same.

The user has to be signed in through Supabase Auth before the calendar loads anything, or the select policy returns zero rows. Sign in with whatever method you use (email, OAuth, magic link), then create the calendar.

Using It Inside a Framework

In React, Vue, Svelte or Angular, create the instance in the mount hook and destroy it on unmount. A React version of the setup:

import { useEffect, useRef } from 'react'; import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; import { supabase, fetchEvents } from './calendarData'; export default function SupabaseCalendar() { const containerRef = useRef(null); const calendarRef = useRef(null); useEffect(() => { const calendar = new SimpleCalendarJs(containerRef.current, { defaultView: 'week', fetchEvents }); calendarRef.current = calendar; const channel = supabase .channel('calendar-events') .on('postgres_changes', { event: '*', schema: 'public', table: 'events' }, () => { calendar.refresh(); }) .subscribe(); return () => { supabase.removeChannel(channel); calendar.destroy(); }; }, []); return <div ref={containerRef} style={{ height: '640px' }} />; }

In Next.js or another SSR framework, this component has to run on the client only. The React calendar guide covers the details, and if the calendar lives inside a product, see adding a calendar to a SaaS dashboard.

Where SimpleCalendarJS Fits, and Where It Doesn't

For a Supabase-backed app with personal or team calendars, bookings or schedules, SimpleCalendarJS covers the UI: four views, drag and drop with mouse and touch, a list view for upcoming events, dark mode through the uc-dark class, and theming with CSS variables. It works the same in vanilla JS or any framework, so the Supabase code stays the same whichever framework you pick.

What it won't do for you:

  • No recurring events. Expand recurrences before returning them from fetchEvents.
  • No resource or timeline views. For "rooms × hours" or "staff × days" layouts, a library with resource views (such as FullCalendar Premium or Bryntum) is the better choice.
  • No time zone option. Events show in the browser's local time.

On licensing: SimpleCalendarJS is free for personal, educational and open source projects. Commercial use (SaaS, client sites, internal tools) needs a license; see pricing. You can try the options in the sandbox or read the docs.

Need a calendar in your app?

SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.

Live Updates With Supabase Realtime

If two people share a calendar, or one person has it open in two tabs, changes should show up without a reload. Supabase Realtime's Postgres Changes feature pushes inserts, updates and deletes to subscribed clients.

First, add the table to the supabase_realtime publication (or toggle it on under Publications in the dashboard):

alter publication supabase_realtime add table public.events;

Then subscribe and refresh the calendar when anything changes. Several changes can arrive close together (including echoes of your own writes), so a short debounce avoids redundant fetches:

let refreshTimer; function scheduleRefresh() { clearTimeout(refreshTimer); refreshTimer = setTimeout(() => calendar.refresh(), 250); } const channel = supabase .channel('calendar-events') .on( 'postgres_changes', { event: '*', schema: 'public', table: 'events' }, scheduleRefresh ) .subscribe((status, err) => { if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') { console.error('Realtime subscription failed', status, err); } }); // When the calendar goes away (route change, logout): // supabase.removeChannel(channel); // calendar.destroy();

Refreshing instead of patching the event list from the payload is a deliberate choice. The calendar re-runs the same RLS-protected range query, so it can't show a row the user isn't allowed to see, and you don't have to write merge logic for moved, resized or deleted events.

Things to know before you rely on it:

  • RLS and DELETE. The Postgres Changes guide notes that RLS policies are not applied to DELETE events, because Postgres can't check access to a row that no longer exists. Refreshing on a delete is harmless. Just don't build UI that shows the deleted row's data from the payload.
  • Filtering deletes needs replica identity full. If you add a filter to the subscription, it won't apply to DELETE events unless you run alter table public.events replica identity full;.
  • Scale. Supabase itself says Postgres Changes are simple to use but have limitations as you scale, and recommends Broadcast for most use cases. For a few hundred users on shared calendars, Postgres Changes is fine. For high-traffic apps, read the Realtime docs before you commit.

Time Zones, All-Day Events and Other Gotchas

Time zones. timestamptz plus new Date(row.start_at) gives you the right instant, and SimpleCalendarJS renders it in the browser's local time. If your users must see events in a specific zone (say, a venue's local time for every visitor), convert the dates in toCalendarEvent before returning them. Neither Postgres nor the calendar will do that for you.

All-day events. Store them with all_day = true and midnight-to-midnight times computed in the user's local zone, and build the dates with new Date(year, month, day). Avoid date-only strings like '2026-11-22': new Date() reads them as UTC midnight, so west of UTC they land on the previous day.

Long ranges in list view. The list view asks for listDaysForward days (30 by default). The overlap query handles that the same way as a month, but if users have thousands of events, select only the columns the calendar shows, as the example does, and fetch descriptions on demand.

Constraint errors are your validation. When the check constraint rejects an event, supabase-js returns an error with a message. Show it, then refresh() so a dragged event snaps back to its saved position.

Recurring events. Postgres has nothing calendar-specific for recurrence. Store a rule alongside the event and expand occurrences for the requested start/end window, either in a Postgres function you call with .rpc() or in fetchEvents itself.

Sources & Further Reading

Image Credits

Image free to use under the Pexels License.

Frequently Asked Questions

Can I build a Supabase calendar without my own backend server?

Yes. supabase-js talks to your database straight from the browser using the publishable key. Row Level Security policies on the events table decide what each signed-in user can read and write, so you don't need an API server of your own for a basic personal or team calendar.

Is it safe to put the Supabase key in front-end calendar code?

The publishable key (sb_publishable_...) and the legacy anon key are meant for browsers, and they can only reach what your RLS policies allow. Never ship a secret key (sb_secret_...) or the legacy service_role key to the client: they bypass RLS completely.

Should calendar event times use timestamp or timestamptz in Postgres?

Use timestamptz. Postgres turns the input into UTC, stores it, and returns it with an offset, so new Date() in the browser gets the exact instant. Plain timestamp has no time zone, so the same row can show up at different times for users in different zones.

How do I store recurring events in Supabase?

Postgres has no built-in recurrence type for calendars. A common approach is to store the base event plus a rule column (for example an RRULE string), then expand the occurrences for the requested date range in a database function or on the client before handing them to the calendar.

How do I share one Supabase calendar between team members?

Add a team_id column to events and a team_members table. Then write RLS policies that check whether the current auth.uid() is a member of the row's team, instead of comparing auth.uid() to user_id. Index team_id so these policy checks stay fast.

Is SimpleCalendarJS free to use with Supabase?

SimpleCalendarJS is free for personal, educational and open source projects, whatever backend you use. Commercial use, such as a SaaS product, a client website or an internal company tool, needs a paid license per project. See the pricing section on simplecalendarjs.com.

Add a calendar to your app today

Free for personal projects. $49/year or $199 lifetime per commercial project.

Keep Reading