How to Load Calendar Events From a REST API in JavaScript
By SimpleCalendarJS Team
Have the calendar send your API the visible date range as ISO `start` and `end` parameters. The server returns only the events that overlap that range, you map each row to the calendar's event shape, and you fetch again after any create, move or delete. In SimpleCalendarJS that's one async `fetchEvents(start, end)` function plus `refresh()`.
Hard-coding an events array is fine for a demo, but real calendars get their data from a backend: bookings, shifts, deadlines, publishing dates. To load calendar events from an API in JavaScript, you need more than one fetch call. You need an endpoint that filters by date range, a mapping from your database fields to the calendar's event shape, correct time zone handling, and a plan for failed or slow requests. This guide covers each of those pieces with code you can adapt, whichever calendar library you use.
What a Calendar Needs From Your API
A calendar shows a window of time: about six weeks in a month grid, seven days in week view, one day in day view. Each time the user navigates, the visible window changes. So the contract between the calendar and your API comes down to one question: "which events overlap this range?"
That gives you three rules:
- Send the visible range to the server. Use two query parameters,
startandend, as ISO 8601 strings. FullCalendar's JSON feed uses this same convention: it sendsstartandendas GET parameters with ISO 8601 values by default. An endpoint built this way works with most calendar libraries. - Filter on the server. Don't download a year of events to show one week. The server returns only events that overlap the range.
- Return a flat list. Each item needs at least an id, a title, a start and an end. Anything else (color, description, a link) is optional.
If you're still choosing how events should look and be filtered once they're in the browser, JavaScript Event Calendar: Load, Display and Filter Events covers the display side. This post is about the API side.
Designing the REST Endpoint for a Date Range
The most common bug in calendar endpoints is the date filter. Filtering on start >= rangeStart AND start < rangeEnd drops any event that begins before the window and continues into it, such as a three-day conference starting on the last day of the previous month. The correct test is an overlap:
SELECT id, name, starts_at, ends_at, all_day, color FROM events WHERE starts_at < :range_end AND ends_at > :range_start ORDER BY starts_at;
An event overlaps the window if it starts before the window ends and ends after the window starts. With an index on (starts_at, ends_at), this query stays fast even for large tables.
Here is a minimal Express 5 endpoint. The in-memory array stands in for your database:
// server.js — Express 5 (requires Node.js 18+) import express from 'express'; const app = express(); app.use(express.json()); // Stand-in for a database table. Timed events are stored in UTC. const events = [ { id: 1, name: 'Sprint planning', starts_at: '2026-11-23T09:00:00Z', ends_at: '2026-11-23T10:30:00Z', all_day: false, color: '#4f46e5' }, { id: 2, name: 'Release freeze', starts_at: '2026-11-25', ends_at: '2026-11-27', all_day: true, color: '#dc2626' }, ]; function parseDate(value) { if (typeof value !== 'string') return null; const date = new Date(value); return Number.isNaN(date.getTime()) ? null : date; } app.get('/api/events', (req, res) => { const start = parseDate(req.query.start); const end = parseDate(req.query.end); if (!start || !end || end <= start) { return res.status(400).json({ error: 'start and end must be valid ISO dates, start < end' }); } const visible = events.filter( (e) => new Date(e.starts_at) < end && new Date(e.ends_at) > start ); res.json(visible); }); app.listen(3000);
Two details matter here. First, validate the query parameters. The Express docs warn that req.query is built from user-controlled input and every value in it is untrusted: start might be missing, an array, or garbage. Second, return a 400 for a bad range rather than an empty list, so client bugs show up during development instead of looking like "no events".
A real API would add PATCH /api/events/:id and POST /api/events for moving and creating events. The full example below uses both.
Need a calendar in your app?
SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.
Load Calendar Events From an API in JavaScript With fetch
On the client, the fetch function takes the visible range and returns events. Three things from the Fetch API trip people up:
fetch()does not reject on HTTP errors. MDN is explicit: it rejects on network failures, not on a404or500. Checkresponse.okyourself.- Build query strings with
URLSearchParams, not string interpolation. It percent-encodes values, and an ISO string with a+05:30offset would otherwise have its+read as a space. Date.prototype.toISOString()always returns UTC with aZsuffix (2026-11-23T09:00:00.000Z), which is the unambiguous format you want on the wire.
A library-independent version looks like this:
// events-api.js export async function getEvents(start, end, { signal } = {}) { const params = new URLSearchParams({ start: start.toISOString(), end: end.toISOString(), }); const response = await fetch(`/api/events?${params}`, { headers: { Accept: 'application/json' }, signal, }); if (!response.ok) { throw new Error(`Loading events failed: HTTP ${response.status}`); } const rows = await response.json(); return rows.map(toCalendarEvent); }
Cancelling stale requests in a hand-rolled calendar
If you render the calendar yourself and the user clicks "next" three times quickly, three requests are in flight. They can resolve out of order and show the wrong week. Use an AbortController so that each new range cancels the previous request:
import { getEvents } from './events-api.js'; let controller = null; async function loadRange(start, end) { controller?.abort(); controller = new AbortController(); try { const events = await getEvents(start, end, { signal: controller.signal }); renderEvents(events); // your own rendering code } catch (err) { if (err.name === 'AbortError') return; // superseded by a newer range showError(err.message); } }
An aborted fetch rejects with an error named AbortError, so you can ignore it and still report real failures. A calendar library that calls your fetch function for you usually handles ordering itself, so check its docs before adding cancellation logic on top.
Mapping API Fields to Calendar Events
Your database rarely matches the calendar's field names. Keep the translation in one function so the rest of your code never has to know about either shape:
| API field (example) | Calendar field | Notes |
|---|---|---|
id | id | Must be unique; needed for drag & drop |
name | title | Required |
starts_at | start | Date object or date string |
ends_at | end | Required; events without a valid end won't render |
all_day | allDay | Boolean |
color | color | Hex background color |
notes | description | Often shown as a tooltip |
| anything else | keep it | Useful in click handlers (e.g. url, ownerId) |
// Parse 'YYYY-MM-DD' as local midnight, not UTC midnight. function parseLocalDate(ymd) { const [y, m, d] = ymd.split('-').map(Number); return new Date(y, m - 1, d); } export function toCalendarEvent(row) { const allDay = row.all_day === true; return { id: row.id, title: row.name, start: allDay ? parseLocalDate(row.starts_at) : new Date(row.starts_at), end: allDay ? parseLocalDate(row.ends_at) : new Date(row.ends_at), allDay, color: row.color || '#4f46e5', description: row.notes || '', ownerId: row.owner_id, // extra field, passed back in callbacks }; }
Dates and Time Zones: Where API Events Go Wrong
Most "my event is on the wrong day" bug reports come down to how JavaScript parses date strings. MDN's Date.parse() page spells out the rules:
- A date-only string like
"2026-11-25"is parsed as UTC midnight. In New York that's 7 p.m. on November 24, so an all-day event lands on the previous day. - A date-time string without an offset, like
"2026-11-25T09:00:00", is parsed as local time. - A string with
Zor an offset is parsed as that exact instant.
That leads to a simple policy that works for most apps:
- Store and send timed events in UTC with a
Zsuffix.new Date('2026-11-23T09:00:00Z')becomes the right instant, and the browser displays it in the user's local time. - Store and send all-day events as plain dates, and parse them with the
new Date(year, monthIndex, day)constructor, asparseLocalDatedoes above. An all-day holiday is a calendar date, not an instant. - If users must see a specific zone (a venue's local time, for example, regardless of where the viewer is), convert on the server or with a date library before handing events to the calendar. Most lightweight calendars, SimpleCalendarJS included, display in the browser's local time and have no time zone option.
When you send a moved event back to the server, apply the same split: toISOString() for timed events, and a local YYYY-MM-DD string for all-day events.
Errors, Timeouts and Empty States
A calendar that silently shows an empty grid when the API is down looks like a calendar with no events. Handle three cases differently:
- Network or HTTP error: show a visible message and a retry button.
- Slow server: set a timeout.
AbortSignal.timeout(8000)returns a signal that aborts after 8 seconds. The error's name isTimeoutError, so you can tell it apart from a user-triggeredAbortError. To combine a timeout with manual cancellation,AbortSignal.any([AbortSignal.timeout(8000), controller.signal])aborts when either one fires. - Genuinely no events: an empty array, no error message. In list view, consider an explicit "Nothing scheduled" note.
For authenticated APIs, remember that fetch sends cookies only to the same origin by default (credentials: 'same-origin'). Cross-origin cookies need credentials: 'include', and the server must answer with Access-Control-Allow-Credentials and an explicit origin.
Building It With SimpleCalendarJS
SimpleCalendarJS is built around this pattern. Instead of an events array, you give it one async function, fetchEvents(start, end), which it calls with the visible date range. Results are cached per month grid, so switching between week and day view inside a month already loaded doesn't hit your API again. After any change on the server, refresh() clears the cache and calls fetchEvents again. No method adds or removes a single event: you change your data, then refresh.
The example below loads events from the endpoint above, saves drag-and-drop and resize changes with PATCH, and creates events on slot click with POST:
<p id="calendar-status" hidden> Could not load events. <button id="retry" type="button">Retry</button> </p> <div id="calendar" style="height: 650px"></div>
import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; import { toCalendarEvent } from './map-event.js'; // the mapping function above const API = '/api/events'; const statusEl = document.querySelector('#calendar-status'); async function api(path, options = {}) { const response = await fetch(path, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers }, signal: AbortSignal.timeout(8000), }); if (!response.ok) { throw new Error(`${options.method || 'GET'} ${path}: HTTP ${response.status}`); } return response.status === 204 ? null : response.json(); } function toLocalYmd(date) { const pad = (n) => String(n).padStart(2, '0'); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } const calendar = new SimpleCalendarJs('#calendar', { defaultView: 'week', enabledViews: ['month', 'week', 'day', 'list'], weekStartsOn: 1, enableDragDrop: true, enableResize: true, fetchEvents: async (start, end) => { const params = new URLSearchParams({ start: start.toISOString(), end: end.toISOString(), }); try { const rows = await api(`${API}?${params}`); statusEl.hidden = true; return rows.map(toCalendarEvent); } catch (err) { console.error(err); statusEl.hidden = false; return []; } }, onEventDrop: async (event, oldStart, oldEnd, newStart, newEnd) => { const body = event.allDay ? { starts_at: toLocalYmd(newStart), ends_at: toLocalYmd(newEnd) } : { starts_at: newStart.toISOString(), ends_at: newEnd.toISOString() }; try { await api(`${API}/${event.id}`, { method: 'PATCH', body: JSON.stringify(body) }); } catch (err) { alert('Could not save the change. The event will move back.'); } calendar.refresh(); // show what the server actually stored }, onSlotClick: async (date) => { const name = prompt('Event title'); if (!name) return; const end = new Date(date.getTime() + 60 * 60 * 1000); // 1 hour try { await api(API, { method: 'POST', body: JSON.stringify({ name, starts_at: date.toISOString(), ends_at: end.toISOString(), all_day: false, }), }); calendar.refresh(); } catch (err) { alert('Could not create the event.'); } }, onEventClick: (event) => { console.log('Open your own details panel for', event.id, event.ownerId); }, }); document.querySelector('#retry').addEventListener('click', () => calendar.refresh());
A few notes on this design:
- Call
refresh()after both success and failure inonEventDrop. On success the cache is replaced with server data, which picks up any changes the server made, such as snapping to 15-minute slots. On failure the event moves back to where it was stored. - An empty array returned on error can be cached for that month grid. That's why the retry button calls
refresh(): it clears the cache and asks the API again. prompt()is a placeholder. SimpleCalendarJS has no built-in event form.onSlotClickandonEventClickare the hooks for opening your own modal.- Recurring events must be expanded on the server, or in
fetchEvents, into individual occurrences for the requested range. There's no RRULE support. - The inline
heighton the container gives month view a fixed layout with "+N more" links. Without it, the grid grows to fit every event.
In React, Vue, Svelte or Angular, the same options go into the core class inside the framework's lifecycle hook, and you call destroy() on unmount. Getting Started with SimpleCalendarJS and the docs show the setup for each, and you can try options live in the sandbox. SimpleCalendarJS is free for personal, educational and open source projects. Commercial use (client sites, SaaS, internal tools) requires a license; see pricing.
If you need resource or timeline views, built-in recurrence or server-side time zone handling, a heavier library such as FullCalendar (whose JSON feed follows the same start/end convention) may suit you better. Because the endpoint above follows that convention, switching later costs little.
Need a calendar in your app?
SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.
Adapting the Pattern to Other Data Sources
The same three steps (range in, overlap filter, map out) work beyond your own REST API:
- Third-party calendars: Google Calendar's API also takes a time window. How to Add Google Calendar Events to Your Website walks through that case, including why the API key should stay on the server.
- GraphQL: pass
startandendas variables and keep the same mapping function. - Dashboards with several widgets: if other parts of the page change events, call
refresh()after they save. How to Add a Calendar to a SaaS Dashboard covers that layout.
Whatever the source, keep the mapping function as the only place that knows both shapes. When the backend renames starts_at to start_time, you change one line.
Sources & Further Reading
- Using the Fetch API — MDN Web Docs
- AbortController — MDN Web Docs
- AbortSignal: timeout() static method — MDN Web Docs
- URLSearchParams — MDN Web Docs
- Date.prototype.toISOString() — MDN Web Docs
- Date.parse() — MDN Web Docs
- events (as a json feed) — FullCalendar Docs
- Express 5.x API Reference: Request — Express
- Express 5.x API Reference — Express
Image Credits
- Cover: Close up of programming code on computer screen — Pexels
Image free to use under the Pexels License.
Frequently Asked Questions
How do I send an auth token when fetching calendar events?
Add an Authorization header to the fetch call, for example headers: { Authorization: `Bearer ${token}` }. If your API uses session cookies on the same origin, fetch already sends them, because the default credentials mode is 'same-origin'. For cookies on a different origin, set credentials: 'include'. The server must then allow credentials in its CORS headers.
How do I fix CORS errors when loading calendar events from another domain?
Fix CORS on the server, not in the browser. The API has to return an Access-Control-Allow-Origin header that names your site's origin. If you send cookies with credentials: 'include', it also needs Access-Control-Allow-Credentials: true and an explicit origin rather than '*'. Don't use mode: 'no-cors'. It gives you an opaque response that you can't read.
How do I load recurring events from an API into a JavaScript calendar?
Expand the recurrences into individual occurrences for the requested start–end window, ideally on the server, and return them as ordinary events with unique ids. SimpleCalendarJS has no RRULE support, so it needs the expanded occurrences. Expanding on the server also keeps date-range filtering and permissions in one place.
Can I load events from several APIs into one calendar?
Yes. Inside your fetch function, call every endpoint with Promise.all (or Promise.allSettled, so one failing source doesn't hide the others), map each response to the event shape, and return the combined array. Prefix the ids with the source name, for example 'gh-42' and 'crm-42', so ids from different systems never collide.
Should a calendar events endpoint be paginated?
Usually not. The date range already limits the result to what's visible: a month grid shows about six weeks. If one range can return thousands of rows, raise the server limit for that endpoint or return lighter rows (id, title, start, end, color) and load details when the user clicks. Page-by-page loading makes the grid fill in unevenly.
How do I show new events without the user reloading the page?
The simplest way is polling: call the calendar's re-fetch method on a timer, for example calendar.refresh() every 60 seconds in SimpleCalendarJS, and stop the timer when the calendar is destroyed. For near-real-time updates, push a message over WebSockets or Server-Sent Events and call refresh() when the server reports that something changed.
Add a calendar to your app today
Free for personal projects. $49/year or $199 lifetime per commercial project.



