To use the Microsoft Graph API with Next.js, you can follow these steps:
- Set up a new Next.js project by running npx create-next-app and following the prompts.
- Install the Microsoft Graph JavaScript Client Library by running npm install @microsoft/microsoft-graph-client in your terminal.
- In your Next.js project, create a lib folder and add a file called graph.js to it. This file will contain the functions you need to make requests to the Microsoft Graph API.
- In graph.js, import the Microsoft Graph client library by adding the following line at the top of the file:
const Client = require('@microsoft/microsoft-graph-client');
- To authenticate with the Microsoft Graph API, you'll need to use an Azure AD app that has the necessary permissions. You can follow the steps in the Microsoft Graph documentation to create an Azure AD app and get the necessary credentials.
- In graph.js, use the credentials from your Azure AD app to create an instance of the Microsoft Graph client:
const client = Client.init({
authProvider: (done) => {
done(null, process.env.AZURE_CLIENT_ID, process.env.AZURE_CLIENT_SECRET);
}
});
Now you can use the client instance to make requests to the Microsoft Graph API. For example, to get the current user's profile, you can use the following code:
async function getUserProfile() {
try {
const user = await client.api('/me').get();
return user;
} catch (error) {
console.error(error);
}
}
In your Next.js pages, you can import the getUserProfile function and use it to make requests to the Microsoft Graph API.
I hope this helps!
Regards,