Microsoft Graph Node.js Express Sample Application
repository·main·Indexed 41 days ago
https://github.com/microsoftgraph/msgraph-sample-nodeexpressappA sample application demonstrating how to integrate the Microsoft Graph JavaScript SDK into a Node.js Express environment to access Office 365 data. It features authentication using @azure/msal-node, session management with express-session, and examples of interacting with Microsoft Graph APIs for calendars and user profiles.
What's inside Microsoft Graph Node.js Express Sample
- This sample project demonstrates how to use the Microsoft Graph JavaScript SDK to access data in Office 365 from a Node.js Express application. It is designed to show the integration between a Node.js backend and Microsoft Graph APIs.
Prerequisites for running the sample
mainBefore running the project, ensure you have the following:
- Node.js: Installed on your development machine.
- Microsoft Account: Either a personal Microsoft account (e.g., Outlook.com) or a Microsoft work or school account.
If you do not have an account, you can sign up for a personal account or join the Microsoft 365 Developer Program for a free subscription.
Configure and install the sample
mainFollow these steps to set up your environment variables and dependencies:
- Rename the
example.envfile to.env. - Open
.envand update the following placeholders with the values from your Azure App Registration:- Replace
YOUR_CLIENT_ID_HEREwith your Application (client) ID. - Replace
YOUR_CLIENT_SECRET_HEREwith your client secret value.
- Replace
- Navigate to the
graph-sampledirectory in your terminal. - Install the required dependencies using
npm install.
npm install- Rename the
Register a web application in Azure Active Directory
mainTo allow the application to authenticate with Microsoft Graph, you must register it in the Azure Active Directory admin center:
- Navigate to the Azure Active Directory admin center.
- Under Manage, select App registrations and then New registration.
- Configure the registration with these specific values:
- Name:
Node.js Graph Sample - Supported account types:
Accounts in any organizational directory and personal Microsoft accounts - Redirect URI: Set type to
Weband value tohttp://localhost:3000/auth/callback
- Name:
- Click Register.
- Copy the Application (client) ID; you will need this for configuration.
- Under Manage, select Certificates & secrets and click New client secret.
- Provide a description, select an expiration, and click Add.
- IMPORTANT: Copy the client secret value immediately. It will not be visible again after you leave the page.
Run the sample application
mainOnce configured, you can start the application and access it in your browser:
- Run the application using
npm start. - Open your browser and navigate to
http://localhost:3000.
npm start- Run the application using
Configure session and flash middleware
mainThe application uses
express-sessionfor session management andconnect-flashfor temporary messaging (like error notifications).Warning: The current implementation uses the default in-memory session store, which is not suitable for production environments. In production, you should use a store like Redis or a database.
Session configuration used:
secret: A string used to sign the session ID cookie.resave:falsesaveUninitialized:falseunset:'destroy'
app.use(session({ secret: 'your_secret_value_here', resave: false, saveUninitialized: false, unset: 'destroy' })); app.use(flash());Configure MSAL for Microsoft Graph authentication
mainThe application uses
@azure/msal-nodeto handle authentication via aConfidentialClientApplication. Configuration is driven by environment variables and is stored inapp.locals.msalClientfor access throughout the application.Required environment variables:
OAUTH_CLIENT_ID: The Client ID of your registered Azure AD application.OAUTH_AUTHORITY: The authority URL (e.g.,https://login.microsoftonline.com/{tenantId}).OAUTH_CLIENT_SECRET: The Client Secret for your application.
Note: The sample uses an in-memory
app.locals.usersobject to store logged-in users. For production, use a persistent storage mechanism.const msalConfig = { auth: { clientId: process.env.OAUTH_CLIENT_ID || '', authority: process.env.OAUTH_AUTHORITY, clientSecret: process.env.OAUTH_CLIENT_SECRET }, system: { loggerOptions: { loggerCallback(loglevel, message, containsPii) { if (!containsPii) console.log(message); }, piiLoggingEnabled: false, logLevel: msal.LogLevel.Verbose, } } }; // Create msal application object app.locals.msalClient = new msal.ConfidentialClientApplication(msalConfig);Configure the server port via environment variables
mainThe application determines its listening port using the
PORTenvironment variable. IfPORTis not provided, it defaults to3000. The server can be configured to use a numeric port or a named pipe.# Example: Running the app on port 8080 PORT=8080 npm startTroubleshoot server startup errors
mainWhen starting the server, the application handles specific system errors related to port binding. If you encounter these errors, check the following:
EACCES: The specified port or pipe requires elevated privileges (e.g., trying to use port 80 without sudo).EADDRINUSE: The specified port or pipe is already being used by another process.
Use the eventDateTime Handlebars helper
mainTo display date and time values returned by the Microsoft Graph API in your Handlebars (
.hbs) templates, use theeventDateTimehelper. This helper parses ISO date strings and formats them into a human-readable format:M/d/yy h:mm a.Example usage in a template:
{{eventDateTime .start.dateTime}}var hbs = require('hbs'); var dateFns = require('date-fns'); // Helper to format date/time sent by Graph hbs.registerHelper('eventDateTime', function(dateTime) { const date = dateFns.parseISO(dateTime); return dateFns.format(date, 'M/d/yy h:mm a'); });Define the home route in the Express router
mainThe index router defines the root path (
/) for the application. When aGETrequest is made to/, it renders theindexview template and passes aparamsobject containing{ active: { home: true } }. This object is typically used by the view engine to manage active navigation states in the UI.var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { let params = { active: { home: true } }; res.render('index', params); }); module.exports = router;Application Route Structure
mainThe Express application is organized into several functional routers:
/: Handled byindexRouter(Home/Index)./auth: Handled byauthRouter(Authentication logic/MSAL flows)./calendar: Handled bycalendarRouter(Microsoft Graph Calendar interactions)./users: Handled byusersRouter(User management/profile).
app.use('/', indexRouter); app.use('/auth', authRouter); app.use('/calendar', calendarRouter); app.use('/users', usersRouter);