Microsoft Graph API - JavaScript Library - for Nextjs?

Asqueroso 1 Reputation point
2022-12-21T19:27:01.127+00:00

Im looking to implement Microsoft Graph API with Nextjs 13.
I see there is a React SPA example here.
https://github.com/microsoftgraph/msgraph-sample-reactspa

I would like to port this over to nextjs but it comes along with a bit of 'bloat' such as bootstrap and other stylings.
Im also not sure how to 'extract' only the fundamental parts over to the nextjs app.

I simply want a very very basic startup to get me going. a sign in and sign out example with very little 'bloat'.
Would anyone know how i can implement MS GRAPH API for Nextjs?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,503 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Ali AlEnezi 1,061 Reputation points
    2022-12-21T20:39:12+00:00

    To use the Microsoft Graph API with Next.js, you can follow these steps:

    1. Set up a new Next.js project by running npx create-next-app and following the prompts.
    2. Install the Microsoft Graph JavaScript Client Library by running npm install @microsoft/microsoft-graph-client in your terminal.
    3. 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.
    4. 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,


  2. 2022-12-23T11:43:04.237+00:00

    Here is an example for Authentication App with Next.js and Microsoft Graph:

    https://microsoft.github.io/MicrosoftCloud/tutorials/docs/Authentication-App-With-NextJs-And-Microsoft-Graph/

    Hope this helps

    0 comments No comments