Stepes to Create Project
Step 1: Create a folder application by using this command
mkdir myapp
Step 2: Navigate to project directory
cd myapp
Step 3: Install the necessary packages/libraries in your project using the following commands.
npm i express googleapis
Project Structure:
Step 4: Create an index.js file. This is going to be the main file where we will integrate Google Calendar. At first, we will view events. In this file the logic sequence is :
- Require necessary packages like express and googleapis.
- Declare all necessary credentials from JSON “service key file” such as private key, client email, etc.
- Use project number and calendar ID which we had acquired in previous steps.
- Declare a JWT(JSON Web Token) client using credentials. This JWT client will use service account credentials to authenticate our application to Google servers.
- The SCOPE defines the level of authorization associated with the API call using the JWT client. Since we will first display upcoming events, the SCOPE is “read-only”.
- The JWT client will be used to issue a request to Google servers.
- Google server will return an access token.
- This access token will be used to call Google API.
- Define a calendar object using project number and JWT client.
- Declare home route which will display 10 upcoming events added to the calendar ordered by their start time. If there is no event scheduled for a future or current date, then “No upcoming events found” will be displayed.
- The events are accessed by calendar.events.list. The results returned from this call will be returned to the browser using JSON.stringify.
Example: Implementation to show integration of google calender in nodejs.
//index.js code for integrating Google Calendar
const express = require('express');
const { google } = require('googleapis');
const app = express();
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
const GOOGLE_PRIVATE_KEY="<private-key>"
const GOOGLE_CLIENT_EMAIL = "<client-email>"
const GOOGLE_PROJECT_NUMBER = "<project-number>"
const GOOGLE_CALENDAR_ID = "<calendar-id>"
const jwtClient = new google.auth.JWT(
GOOGLE_CLIENT_EMAIL,
null,
GOOGLE_PRIVATE_KEY,
SCOPES
);
const calendar = google.calendar({
version: 'v3',
project: GOOGLE_PROJECT_NUMBER,
auth: jwtClient
});
app.get('/', (req, res) => {
calendar.events.list({
calendarId: GOOGLE_CALENDAR_ID,
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (error, result) => {
if (error) {
res.send(JSON.stringify({ error: error }));
} else {
if (result.data.items.length) {
res.send(JSON.stringify({ events: result.data.items }));
} else {
res.send(JSON.stringify({ message: 'No upcoming events found.' }));
}
}
});
});
app.listen(3000, () => console.log(`App listening on port 3000!`));
// This code is contributed by Yashi Shukla
The private key, client email can be obtained from JSON file. The calendar ID and project number which you previously stored will be used here.
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js
Output: Output can be viewed on your browser by using this link: http://localhost:3000/
This route will display 10 upcoming events on the calendar or “No upcoming events found” if no events have been added.
Since this is a newly created calendar, there are no upcoming events.
Step 5: Insert new events. Google offers different methods for managing and controlling events being added to the calendar. We can add new events by using the calendar.events.insert() method. We will have to make a few changes in the role of the user added in step 6 of setting up Google Calendar. Go back to the “Share with specific people” section and change the role of your service account from “See all event details” to “Make changes to events”.
Step 6: Since we are now going to edit events, our application needs to be authenticated as a service account. For this type, the following in command prompt(root directory of project) and in place of KEY_PATH, put the entire path of your JSON service key file.
set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
Step 7: Create a new route for adding an event(/createEvent) in index.js. For simplicity, we will hard code the details of the event. As per documentation for Calendar API, the event object can be defined as:
//A sample event object for calendar
var event = {
'summary': 'My first event!',
'location': 'Hyderabad,India',
'description': 'First event with nodeJS!',
'start': {
'dateTime': '2022-01-12T09:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'end': {
'dateTime': '2022-01-14T17:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'attendees': [],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
};
You can give your own values of date, time, location, description as per your choice.
Step 7: The JWT client defined a “read-only” scope for API calls. However, if we want to add new events, a “read-only” scope will not be sufficient.
- So now let’s declare another client “auth”, which contains the credentials for authentication such as the path of JSON service key file and authorization SCOPE as “https://www.googleapis.com/auth/calendar” for full access to Google Calendar API.
- auth client will perform the background process similar to JWT client of requesting for access token from Google authentication servers to make API call.
The following is the code for declaring “auth” client:
//Creating an aunthenticated client to call events.insert()
const auth = new google.auth.GoogleAuth({
keyFile: '<FULL-PATH-OF-JSON-FILE>',
scopes: 'https://www.googleapis.com/auth/calendar', //full access to edit calendar
});
auth.getClient().then(a=>{
calendar.events.insert({
auth:a,
calendarId: GOOGLE_CALENDAR_ID,
resource: event,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.data);
res.jsonp("Event successfully created!");
});
})
In the final code of index.js we have:
- Created a new route “/createEvent” for allowing users to add new events to the calendar.
- Since we are using only NodeJS, the event details will be hardcoded. An event object is declared with necessary values for key fields like description, name, summary, start time, end time, etc.
- This event can be added by our application by using “calendar.events.insert“. This operation is authenticated and authorized by an instance of google.auth.GoogleAuth “auth” client.
- After adding an event, when the user again visits the home route, the new event details will be displayed(provided the start date for the event is on the current date or future date).
Below is the final code for index.js:
//Final index.js code
const express = require('express');
const { google } = require('googleapis');
const app = express();
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
const GOOGLE_PRIVATE_KEY="<private-key>";
const GOOGLE_CLIENT_EMAIL = "<client-email>"
const GOOGLE_PROJECT_NUMBER = "<project-number>"
const GOOGLE_CALENDAR_ID = "<calendar-id>"
const jwtClient = new google.auth.JWT(
GOOGLE_CLIENT_EMAIL,
null,
GOOGLE_PRIVATE_KEY,
SCOPES
);
const calendar = google.calendar({
version: 'v3',
project: GOOGLE_PROJECT_NUMBER,
auth: jwtClient
});
app.get('/', (req, res) => {
calendar.events.list({
calendarId: GOOGLE_CALENDAR_ID,
timeMin: (new Date()).toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (error, result) => {
if (error) {
res.send(JSON.stringify({ error: error }));
} else {
if (result.data.items.length) {
res.send(JSON.stringify({ events: result.data.items }));
} else {
res.send(JSON.stringify({ message: 'No upcoming events found.' }));
}
}
});
});
app.get("/createEvent",(req,res)=>{
var event = {
'summary': 'My first event!',
'location': 'Hyderabad,India',
'description': 'First event with nodeJS!',
'start': {
'dateTime': '2022-01-12T09:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'end': {
'dateTime': '2022-01-14T17:00:00-07:00',
'timeZone': 'Asia/Dhaka',
},
'attendees': [],
'reminders': {
'useDefault': false,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
};
const auth = new google.auth.GoogleAuth({
keyFile: '<full-path-of-JSON-file>',
scopes: 'https://www.googleapis.com/auth/calendar',
});
auth.getClient().then(a=>{
calendar.events.insert({
auth:a,
calendarId: GOOGLE_CALENDAR_ID,
resource: event,
}, function(err, event) {
if (err) {
console.log('There was an error contacting the Calendar service: ' + err);
return;
}
console.log('Event created: %s', event.data);
res.jsonp("Event successfully created!");
});
})
})
app.listen(3000, () => console.log(`App listening on port 3000!`));
// This code is contributed by Yashi Shukla
Now Checking event created. Open your browser and go to http://localhost:3000/createEvent.
Output:
The following output will be shown
Now as you remember, previously in the output section, “No upcoming events” was displayed. Now again go to http://localhost:3000/. Your newly created event details will be displayed!
Proceed to Google Calendar and you can also see the newly created event added there.
Final Output:
How to Integrate Google Calendar in Node.js ?
Integrating Google Calendar into a Node.js application allows you to create, modify, and manage calendar events programmatically. This can be useful for various applications, such as scheduling software, personal organizers, or any app that needs to manage events. In this article, we will walk through the steps required to integrate Google Calendar in a Node.js application.
Contact Us