JavaScript Library
How to Generate Calendar Events Programmatically for Browser and NodeJS using JavaScript?
Featuring a small JavaScript library to build calendar events that you can share on the website ou by e-mail.
Recently I had two use cases that I needed to implement for my company. To give a bit of context we are providing links between users and sports coaches that are organizing sports sessions.
When a user books a session it could be nice to have a reminder of this event in its agenda.
- Users should have a button to add some events to their personal calendar (Outlook, Google Calendar, iOS calendar, …) on the website.
- When having booked for an event, they have to receive something by e-mail to add this event to their calendar.
At first glance, it looks pretty simple but when you have no knowledge about how this works it’s a bit awkward.
Depending on the calendar provider, the technique gets a bit different, some are just URL based and some others require a file with a specific format.
After searching on the topic, I’ve come to the conclusion that for Google it’s pretty straightforward and you just need to build a specific URL.
For Apple calendars and Outlook you need a .ics
file, which is a special file that is handled by such calendar apps.
Knowledge about calendars events
The following repository gives some details about how this works and the specifications about the implementation if you want a homemade algorithm.
But if you need a JavaScript library that is simple and pretty straightforward I could only recommend using DateBook
which is probably the most advanced library to deal with such needs in JavaScript.
At first, this was not SSR ready, but I’ve contributed by working with the owner to make it work server-side. Which is great and allows us to use it in e-mails templates.
DateBook is a dead-simple library that will save you from headaches, it’s easy as instantiating one class and call some generation function on it.
const config: CalendarOptions = {
title: 'Happy Hour',
location: 'The Bar, New York, NY',
description: 'Let\'s blow off some steam with a tall cold one!',
start: new Date('2022-07-08T19:00:00'),
end: new Date('2022-07-08T23:30:00'),
// an event that recurs every two weeks:
recurrence: {
frequency: 'WEEKLY',
interval: 2
}
}
const icalendar = new ICalendar(config)
It brings support for GoogleCal, Outlook, and of course IOS calendars.
The personalization can get deep, with recurrence and things like that, all you have to do is populate the class constructor with the required data.
Using Datebook you can render files on NodeJS or directly in the browser, this allows you to use it in e-mails, which is nice for a booking site.
You can also imagine making an HTTP REST endpoint server-side that generates an ICS file on the flight, that people can subscribe to as a stream.
I won’t develop much more here just to repeat what’s is already described, feel free to read the documentation which is really well detailed.