Back to Blog
Modern laptop on wooden desk with code displayed
Tutorial
8 min read

Firebase Calendar Events: Show Firestore Data in a JS Calendar

By SimpleCalendarJS Team

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

Store each event in Firestore with `start` and `end` as Timestamps. Query only the documents that overlap the calendar's visible date range, convert them with `toDate()`, and return them from the calendar's async events callback. To make changes show up live, swap `getDocs` for an `onSnapshot` listener and re-render when it fires.

You keep your app's data in Cloud Firestore and now need those records on a real calendar: month, week and day views, with dragging to reschedule and updates that show up without a reload. Getting Firebase calendar events right comes down to four decisions: how you store dates, how you query a date range, how you keep the view in sync and how you secure it. This guide covers each one with working modular-SDK code.

The calendar code uses SimpleCalendarJS, but the data model, queries and rules work with any calendar library that loads events for a date range.

How Firebase Calendar Events Should Be Stored

Give each event its own document in a top-level events collection. Firestore has a native date-and-time type that sorts chronologically and stores values with microsecond precision, so use Timestamps for start and end, not strings or epoch numbers.

// events/{eventId} { ownerId: 'uid_123', // Firebase Auth UID title: 'Design review', start: Timestamp.fromDate(new Date(2026, 10, 24, 10, 0)), end: Timestamp.fromDate(new Date(2026, 10, 24, 11, 30)), allDay: false, color: '#4f46e5', description: 'Room 2 / Meet link in invite' }

The SDK's Timestamp class gives you everything you need to convert in both directions. Timestamp.fromDate(date) builds a Timestamp from a JavaScript Date, and timestamp.toDate() turns it back, dropping anything below the millisecond. That's fine for a calendar.

All-day events and time zones

A Timestamp is a single point in time with no time zone attached. If you store an all-day event as "midnight on 24 November" in Lisbon, a user in New York sees it start at 7 p.m. on the 23rd. A dependable fix is to keep the Timestamps for querying and add plain date strings for display:

{ ownerId: 'uid_123', title: 'Company offsite', allDay: true, startDay: '2026-11-26', // shown as-is in every time zone endDay: '2026-11-27', start: Timestamp.fromDate(new Date(2026, 10, 26)), // used for range queries end: Timestamp.fromDate(new Date(2026, 10, 27)) }

Don't pass '2026-11-26' straight to new Date(). A date-only string is parsed as UTC midnight, so anywhere west of UTC it lands on the previous day. Split it and build a local date, as in the parseLocalDay helper below.

Querying Only the Visible Date Range

A calendar never needs the whole collection. It needs the events that overlap the dates on screen: those that start before the end of the range and end after its start. Firestore gives you two ways to express that.

Option A: an overlap query on two fields

Firestore supports range and inequality filters on more than one field in a single query, so you can write the overlap check directly:

query( collection(db, 'events'), where('ownerId', '==', uid), where('start', '<', Timestamp.fromDate(rangeEnd)), where('end', '>', Timestamp.fromDate(rangeStart)) );

This query is exact. The catch is how Firestore runs it. According to its documentation on multi-field range queries, only the most selective range field narrows the index scan, and less selective fields still filter results but don't reduce the scan. Here start < rangeEnd matches every past event and end > rangeStart matches every future one. As your history grows, Firestore scans more and more index entries to return the same handful of events. Queries with more than one range field are also billed for index entries read, in batches of up to 1,000 per read.

If you cap how long an event can be (say 14 days), every event that overlaps the range must start no earlier than rangeStart − 14 days. That gives you a query with one range field, bounded on both sides:

const MAX_EVENT_DAYS = 14; const DAY_MS = 24 * 60 * 60 * 1000; query( collection(db, 'events'), where('ownerId', '==', uid), where('start', '>=', Timestamp.fromDate(new Date(rangeStart.getTime() - MAX_EVENT_DAYS * DAY_MS))), where('start', '<', Timestamp.fromDate(rangeEnd)) ); // then on the client: keep only events whose end is after rangeStart

You read a few extra documents (events that ended just before the range), then drop them in one .filter(). The index scan stays the same size whether you have a hundred events or a million.

Option A: two-field overlapOption B: bounded window
Exact results from FirestoreYesNearly; filter end on the client
Range fields in query2 (start, end)1 (start)
Index scan as history growsGrowsStays bounded
Billed for index entriesYes, per 1,000No (one range field)
Constraint on your dataNoneEvents can't exceed the max duration
Good forSmall collections, prototypesProduction calendars

The composite index

Combining ownerId == with a range on start needs a composite index. You don't have to write it by hand: the first time the query runs, it fails with an error that contains a direct link to create the missing index in the Firebase console. Open the link, check the fields and click Create. If you manage indexes in a local file, the Firebase docs remind you to copy console changes back into it and deploy with firebase deploy --only firestore.

Need a calendar in your app?

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

Loading Events Once With getDocs

If your events rarely change, or each user is the only one editing them, a one-off query per visible range is enough. The calendar passes its visible range to fetchEvents, and you return an array:

import { getDocs } from 'firebase/firestore'; async function loadRange(uid, start, end) { const snapshot = await getDocs(rangeQuery(uid, start, end)); return snapshot.docs .map(toCalendarEvent) .filter((event) => event.end > start); } const calendar = new SimpleCalendarJs('#calendar', { fetchEvents: (start, end) => loadRange(uid, start, end), });

SimpleCalendarJS caches results per month grid, so moving back to a month you've already seen doesn't hit Firestore again. After you write to Firestore yourself, call calendar.refresh() to clear the cache and reload. The catch is that changes made by other users or devices won't show up until the next reload. For that you need a listener.

Building It With SimpleCalendarJS

This is the full live version: Firebase Auth for the user, a bounded-window query, an onSnapshot listener that follows the visible range, drag and resize that write back to Firestore, and a basic "click a slot to add an event" flow. The HTML is one container with an inline height, which gives month view a fixed layout with "+N more" links:

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

Install both packages. As of November 2026, the Firestore quickstart pins firebase@13.4.0.

npm install firebase simple-calendar-js
// calendar.js import { initializeApp } from 'firebase/app'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; import { getFirestore, collection, doc, query, where, onSnapshot, addDoc, updateDoc, Timestamp } from 'firebase/firestore'; import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; const app = initializeApp({ // paste your web app config from the Firebase console }); const db = getFirestore(app); const auth = getAuth(app); const eventsRef = collection(db, 'events'); const MAX_EVENT_DAYS = 14; // enforce this when you create or resize events const DAY_MS = 24 * 60 * 60 * 1000; function parseLocalDay(value) { const [y, m, d] = value.split('-').map(Number); return new Date(y, m - 1, d); } function toDayString(date) { const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); return `${date.getFullYear()}-${m}-${d}`; } function toCalendarEvent(snap) { const data = snap.data(); const allDay = Boolean(data.allDay); return { id: snap.id, title: data.title, start: allDay && data.startDay ? parseLocalDay(data.startDay) : data.start.toDate(), end: allDay && data.endDay ? parseLocalDay(data.endDay) : data.end.toDate(), allDay, color: data.color || '#4f46e5', description: data.description || '', }; } function rangeQuery(uid, start, end) { const windowStart = new Date(start.getTime() - MAX_EVENT_DAYS * DAY_MS); return query( eventsRef, where('ownerId', '==', uid), where('start', '>=', Timestamp.fromDate(windowStart)), where('start', '<', Timestamp.fromDate(end)) ); } function startCalendar(uid) { let current = null; // the listener for the range on screen let calendar = null; function watchRange(start, end) { const key = `${start.getTime()}|${end.getTime()}`; // Same range as the active listener: serve what it already has. if (current && current.key === key) { return current.events ?? current.promise; } if (current) current.cancel(); const entry = { key, events: null, resolved: false }; entry.promise = new Promise((resolve, reject) => { const unsubscribe = onSnapshot( rangeQuery(uid, start, end), (snapshot) => { entry.events = snapshot.docs .map(toCalendarEvent) .filter((event) => event.end > start); if (!entry.resolved) { entry.resolved = true; resolve(entry.events); } else { calendar.refresh(); // a later change: re-render from entry.events } }, (error) => { console.error('Firestore listener failed:', error); if (current === entry) current = null; if (!entry.resolved) { entry.resolved = true; reject(error); } } ); entry.cancel = () => { unsubscribe(); if (!entry.resolved) { entry.resolved = true; resolve([]); } }; }); current = entry; return entry.promise; } calendar = new SimpleCalendarJs('#calendar', { defaultView: 'week', enabledViews: ['month', 'week', 'day', 'list'], weekStartsOn: 1, enableDragDrop: true, enableResize: true, autoContrastText: true, fetchEvents: async (start, end) => watchRange(start, end), // Cached months skip fetchEvents, so force a reload to move the listener. onNavigate: () => calendar.refresh(), onViewChange: () => calendar.refresh(), onEventDrop: async (event, oldStart, oldEnd, newStart, newEnd) => { const changes = { start: Timestamp.fromDate(newStart), end: Timestamp.fromDate(newEnd), }; if (event.allDay) { changes.startDay = toDayString(newStart); changes.endDay = toDayString(newEnd); } try { await updateDoc(doc(db, 'events', event.id), changes); } catch (error) { console.error(error); calendar.refresh(); // snap back to what Firestore holds } }, onSlotClick: async (date) => { const title = window.prompt('Event title'); if (!title) return; await addDoc(eventsRef, { ownerId: uid, title, allDay: false, start: Timestamp.fromDate(date), end: Timestamp.fromDate(new Date(date.getTime() + 60 * 60 * 1000)), }); }, onEventClick: (event) => { // open your own edit dialog here console.log('Clicked', event.id, event.title); }, }); return () => { if (current) current.cancel(); calendar.destroy(); }; } let stopCalendar = null; onAuthStateChanged(auth, (user) => { if (stopCalendar) { stopCalendar(); stopCalendar = null; } if (user) stopCalendar = startCalendar(user.uid); });

How the live sync works

  1. The calendar calls fetchEvents(start, end) for the range on screen. watchRange opens an onSnapshot listener for that range and resolves with the first snapshot.
  2. Each later snapshot (another tab, another user, a Cloud Function) updates entry.events and calls calendar.refresh(). The refresh asks for the same range, so watchRange returns the fresh array with no new query.
  3. When the user moves to another range, the old listener is unsubscribed and a new one opens. Firestore's docs are explicit that you should detach listeners you no longer need, both to stop callbacks and to save bandwidth.
  4. Because the calendar caches month grids, onNavigate and onViewChange call refresh() so the listener always follows what's on screen. The key check means a double call only opens one listener.

Why drag and drop feels instant

Firestore fires listeners for local writes immediately, before the backend confirms them. When onEventDrop calls updateDoc, the listener gets a snapshot with the new times straight away and the calendar re-renders. If the write is rejected (for example by a security rule), the catch block refreshes so the event goes back to where Firestore says it is. To tell optimistic data from confirmed data, say to show a "saving…" badge, check snapshot.metadata.hasPendingWrites.

What it costs

According to Firestore's billing docs, a listener is charged a read when a document in its result set is added or updated, and every query costs at least one read even if it returns nothing. Opening a listener for a new range reads every document in it. If the client has been disconnected for more than 30 minutes (with offline persistence on), the reconnect is billed as a brand-new query. The free quota, as of 2026, is 50,000 document reads and 20,000 writes per day, which goes a long way when each view only loads the events on screen.

SimpleCalendarJS works well here because the whole integration goes through one async function. There's no event store to keep in sync and no addEvent/removeEvent calls: you update Firestore and the calendar re-reads. It has zero dependencies, weighs about 14 KB gzipped (around 19 KB with the CSS), and the same code runs in vanilla JS or inside any framework. The license is free for personal, educational and open source projects; commercial use (client sites, SaaS, internal tools) needs a paid license, see pricing. You can try the options in the sandbox before wiring up Firebase.

Need a calendar in your app?

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

Security Rules That Match Your Queries

Firestore security rules are not filters. Firestore checks a query against every document it could return, not the ones it actually returns, and rejects the whole request if any of them would break a rule. That's why the query above includes where('ownerId', '==', uid): the rule demands it, so the query has to state it.

rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /events/{eventId} { allow read: if request.auth != null && request.auth.uid == resource.data.ownerId; allow create: if request.auth != null && request.auth.uid == request.resource.data.ownerId && request.resource.data.end > request.resource.data.start; allow update: if request.auth != null && request.auth.uid == resource.data.ownerId && request.resource.data.ownerId == resource.data.ownerId && request.resource.data.end > request.resource.data.start; allow delete: if request.auth != null && request.auth.uid == resource.data.ownerId; } } }

Two things to note. The update rule stops users from handing an event to someone else by changing ownerId. And if you use the bounded-window query, validate the maximum duration in the code that writes events (the onSlotClick handler, your edit form, or a Cloud Function), because an event longer than MAX_EVENT_DAYS can drop out of the query window.

Using It in React or Vue

Nothing about the Firebase side changes in a framework. startCalendar already returns a cleanup function, so you call it from the component's lifecycle hooks. In React:

import { useEffect } from 'react'; import { startCalendar } from './calendar'; // export it from the module above export default function FirestoreCalendar({ uid }) { useEffect(() => { if (!uid) return; const stop = startCalendar(uid); // creates the calendar and the listener return stop; // unsubscribes and destroys on unmount }, [uid]); return <div id="calendar" style={{ height: 650 }} />; }

In Vue, call it in onMounted and call the returned function in onBeforeUnmount. In Next.js, Nuxt or SvelteKit, run it on the client only. The framework guides cover the details: React and the SSR-safe setups for other frameworks. To use a ref instead of an id, change startCalendar to accept an element; the SimpleCalendarJs constructor takes either a selector or an element.

What This Setup Doesn't Handle

Be clear about the limits before you ship:

  • Recurring events. Firestore has no recurrence type, and SimpleCalendarJS doesn't read RRULEs. Store the rule on a series document and expand the instances that fall within start–end inside fetchEvents (a library like rrule.js can do the expansion) before returning them.
  • Fixed display time zones. The calendar shows dates in the browser's local time and has no time zone option. If events must appear in a venue's time zone, convert them in toCalendarEvent.
  • Resource and timeline views. If you need rooms or people as rows (a scheduler with resource lanes), you need a resource-timeline library such as FullCalendar Premium or Bryntum. The calendar scheduler guide covers that trade-off.
  • Edit forms. onSlotClick and onEventClick give you the date or event, and the dialog is yours to build. window.prompt above is a placeholder.

If you're choosing a backend rather than wiring up an existing one, the same calendar pattern works over plain HTTP in loading calendar events from a REST API and over Postgres in the Supabase calendar tutorial.

Sources & Further Reading

Image Credits

Image free to use under the Pexels License.

Frequently Asked Questions

Can I store event dates as strings in Firestore instead of Timestamps?

You can, but range queries and sorting then follow string order, so they only work for one consistent format like ISO 8601 in a single offset. Timestamps sort by time, store microsecond precision and convert straight to a JavaScript Date with toDate(). Use Timestamps for querying, and keep a separate YYYY-MM-DD string only to display all-day events.

What time zone are Firestore timestamps in?

None. A Firestore Timestamp is a point in time. Calling toDate() gives you a JavaScript Date, which the browser shows in the user's local time zone. To show events in a fixed zone, such as a venue's local time, convert the dates yourself before returning them to the calendar.

How much does Firestore cost for a calendar app?

As of 2026, Firestore's free quota includes 50,000 document reads and 20,000 writes per day. Each query costs at least one read, and a realtime listener costs one read for every document added to or updated in its result set. Querying only the visible range keeps reads roughly in line with the number of events on screen.

How do I build a shared Firestore calendar for a team?

Store an array of user IDs (for example `members`) on each event and query it with `where('members', 'array-contains', uid)` plus your date range filter. Your security rules have to check the same condition, because Firestore rejects any query that could return documents the user isn't allowed to read.

How do I delete a Firestore event from the calendar?

Open your own confirmation or edit dialog from onEventClick, then call deleteDoc(doc(db, 'events', event.id)). If you use an onSnapshot listener, the deleted document drops out of the next snapshot and the calendar re-renders on its own. With a one-off getDocs load, call refresh() after the delete.

Do I need Firebase Authentication to show calendar events?

Not for a public calendar. Your security rules can allow anyone to read an events collection while only signed-in admins can write to it. You only need Auth when each user should see their own events, because your rules and your queries both rely on request.auth.uid.

Add a calendar to your app today

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

Keep Reading