### Local Development Environment Setup Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/examples/opennextjs/README.md Sets up the local development environment for the Next.js application. This involves copying example environment variables, adding development credentials, setting up the local database, and starting the development server. ```bash # Create local environment file cp .env.example .env.local # Add your development credentials echo "MICROSOFT_CLIENT_ID=your_dev_client_id" >> .env.local echo "MICROSOFT_CLIENT_SECRET=your_dev_client_secret" >> .env.local echo "BETTER_AUTH_SECRET=your_dev_secret" >> .env.local echo "BETTER_AUTH_URL=http://localhost:3000" >> .env.local # Set up local database pnpm db:migrate:dev # Start development server pnpm dev ``` -------------------------------- ### Deploy Next.js App to Cloudflare Workers Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/examples/opennextjs/README.md Commands to deploy the Next.js application to Cloudflare Workers. This includes installing dependencies, generating authentication schemas, managing database migrations, and the final deployment step. ```bash # Install dependencies pnpm install # Generate auth schema pnpm auth:generate # Generate and apply database migrations pnpm db:generate pnpm db:migrate:prod # Deploy to Cloudflare Workers pnpm deploy ``` -------------------------------- ### Database Command Examples Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/examples/opennextjs/README.md Provides common database commands for managing the application's database schema and migrations. Includes commands for generating schemas, creating migrations, applying them in different environments, and accessing the database studio. ```bash # Generate auth schema from config pnpm auth:generate # Create migration files pnpm db:generate # Apply migrations pnpm db:migrate:prod # Production (recommended) pnpm db:migrate:dev # Local development # Database studio pnpm db:studio:prod # Production pnpm db:studio:dev # Local ``` -------------------------------- ### Install better-auth-microsoft-graph via npm/yarn/pnpm/bun Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md These commands show how to install the better-auth-microsoft-graph package using different package managers like npm, yarn, pnpm, and bun. This is the initial step required to integrate the library into your project. ```bash npm install better-auth-microsoft-graph # or yarn add better-auth-microsoft-graph # or pnpm add better-auth-microsoft-graph # or bun add better-auth-microsoft-graph ``` -------------------------------- ### Azure App Registration Setup Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md Instructions on how to set up API permissions in Azure App Registration for Microsoft Graph access. ```APIDOC ## Azure App Registration Setup To enable Microsoft Graph access, you need to configure API permissions in your Azure App Registration. ### Required Permissions | Permission | Type | Description | |------------------|-----------|---------------------| | `User.Read` | Delegated | Read user profile | | `Calendars.Read` | Delegated | Read user calendars | | `Contacts.Read` | Delegated | Read user contacts | | `Mail.Read` | Delegated | Read user mail | | `Files.Read` | Delegated | Read user files | **NOTE**: Only add the permissions you need. ### Setup Steps: 1. Go to [Azure Portal](https://portal.azure.com/) → Azure Active Directory → App registrations 2. Click "New registration" and configure your app 3. Set redirect URI to: `https://your-domain.com/api/auth/callback/microsoft` 4. Go to "API permissions" → "Add a permission" → "Microsoft Graph" → "Delegated permissions" 5. Add the permissions listed above 6. Copy your Application (client) ID and create a client secret ``` -------------------------------- ### Advanced Configuration Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md Example TypeScript configuration for initializing better-auth with Microsoft social provider. ```APIDOC ```typescript export const auth = betterAuth({ socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID!, clientSecret: process.env.MICROSOFT_CLIENT_SECRET!, prompt: "consent", // Force permission consent flow scopes: [ "User.Read", "Calendars.Read", "Contacts.Read", "Mail.Read", "Files.Read", // Add more scopes as needed. Only add the permissions you need. ], }, }, plugins: [ microsoft({ debugLogs: true, // Enable debug logging }), ], }); ``` ``` -------------------------------- ### Set Production Environment Variables with Wrangler Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/examples/opennextjs/README.md Configures production environment variables for Microsoft OAuth credentials and Better Auth using Cloudflare Wrangler secrets. This is crucial for securing your deployed application. ```bash npx wrangler secret put MICROSOFT_CLIENT_ID # Enter your client ID when prompted npx wrangler secret put MICROSOFT_CLIENT_SECRET # Enter your client secret when prompted npx wrangler secret put BETTER_AUTH_SECRET # Enter a secure random string when prompted npx wrangler secret put BETTER_AUTH_URL # Enter your production URL, e.g., https://your-app.your-subdomain.workers.dev ``` -------------------------------- ### Customize Microsoft Graph API Requests with OData Queries Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md Demonstrates how to use OData query parameters to customize requests to Microsoft Graph endpoints. Examples include selecting specific fields for user profile, retrieving the latest messages with specific fields, and filtering events by date. ```typescript // Get only specific user profile fields const profile = await authClient.microsoft.me({ query: { $select: "displayName,mail,jobTitle,department", }, }); // Get latest 5 messages with specific fields const messages = await authClient.microsoft.me.messages({ query: { $top: 5, $select: "subject,from,receivedDateTime,isRead", $orderby: "receivedDateTime desc", }, }); // Get events with filtering const events = await authClient.microsoft.me.events({ query: { $filter: "start/dateTime ge '2024-01-01T00:00:00Z'", $orderby: "start/dateTime", $top: 10, }, }); ``` -------------------------------- ### Access Microsoft Graph APIs Client-Side with Better Auth Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md This example illustrates how to use the authenticated client to access various Microsoft Graph APIs, including user profile, calendar events, email messages, contacts, and OneDrive information. It showcases the simplified, typesafe access provided by the better-auth-microsoft-graph library, including OData query support for filtering and sorting. ```typescript useEffect(() => { const fetchMicrosoftData = async () => { // Get user profile const profile = await authClient.microsoft.me(); console.log("User:", profile.data?.data?.displayName); // Get calendar events const events = await authClient.microsoft.me.events({ query: { $top: 10, $orderby: "start/dateTime desc" }, }); console.log("Upcoming events:", events.data?.data?.length); // Get email messages const messages = await authClient.microsoft.me.messages(); console.log("Recent emails:", messages.data?.data?.length); // Get contacts const contacts = await authClient.microsoft.me.contacts({ query: { $filter: "startsWith(displayName,'J')" }, }); console.log("Contacts:", contacts.data?.data?.length); // Get OneDrive info const drive = await authClient.microsoft.me.drive(); console.log("Storage used:", drive.data?.data?.quota?.used); }; fetchMicrosoftData(); }, []); ``` -------------------------------- ### Access User Contacts with Filtering and Pagination Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt This snippet demonstrates how to retrieve a user's contact list from Microsoft Graph API. It shows examples of filtering contacts by their display name, selecting specific properties, ordering the results, and fetching a limited number of contacts. It also includes a method to fetch all contacts using pagination. ```typescript import authClient from "./authClient"; async function getContacts() { // Get all contacts starting with 'J' const contacts = await authClient.microsoft.me.contacts({ query: { $filter: "startsWith(displayName,'J')", $select: "displayName,emailAddresses,mobilePhone,businessPhones", $orderby: "displayName asc", }, }); if (contacts.data?.data) { contacts.data.data.forEach(contact => { console.log(`Name: ${contact.displayName}`); console.log(`Email: ${contact.emailAddresses?.[0]?.address}`); console.log(`Mobile: ${contact.mobilePhone}`); }); } // Get top 50 contacts const allContacts = await authClient.microsoft.me.contacts({ query: { $top: 50, $orderby: "displayName asc", }, }); console.log(`Total contacts fetched: ${allContacts.data?.data?.length || 0}`); } ``` ```typescript import authClient from "./authClient"; async function getAllContactsPaginated() { let allContacts: any[] = []; let skip = 0; const pageSize = 100; let hasMore = true; while (hasMore) { const response = await authClient.microsoft.me.contacts({ query: { $top: pageSize, $skip: skip, $orderby: "displayName asc", $select: "displayName,emailAddresses", }, }); if (response.data?.data && response.data.data.length > 0) { allContacts = allContacts.concat(response.data.data); skip += pageSize; hasMore = response.data.data.length === pageSize; } else { hasMore = false; } } console.log(`Total contacts retrieved: ${allContacts.length}`); return allContacts; } ``` -------------------------------- ### Configure Microsoft Social Provider with Better Auth Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md This snippet shows how to configure Microsoft as a social provider within the Better Auth framework. It specifies the client ID, client secret, and the necessary scopes for accessing Microsoft Graph data. This setup is crucial for enabling authentication with Microsoft services. ```typescript import { betterAuth } from "better-auth"; import { microsoft } from "better-auth-microsoft-graph"; export const auth = betterAuth({ socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID!, clientSecret: process.env.MICROSOFT_CLIENT_SECRET!, scopes: ["User.Read", "Calendars.Read", "Contacts.Read", "Mail.Read", "Files.Read"], }, }, plugins: [microsoft()], }); ``` -------------------------------- ### Configure Client-Side Microsoft Graph Plugin Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Initialize the Microsoft Graph client plugin for frontend API calls within the Better Auth framework. This enables typesafe methods for interacting with Microsoft Graph APIs from the client. ```typescript import { createAuthClient } from "better-auth/react"; import { microsoftClient } from "better-auth-microsoft-graph/client"; const authClient = createAuthClient({ plugins: [microsoftClient()], }); export default authClient; ``` -------------------------------- ### Direct REST API Access to Microsoft Graph (Bash) Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Provides cURL commands for directly accessing Microsoft Graph endpoints. This includes fetching user profiles, calendar events, contacts, messages, and OneDrive information. It demonstrates how to include session tokens and JSON payloads for queries. ```bash # Get user profile curl -X GET https://your-domain.com/api/auth/microsoft/me \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" # Get calendar events with query parameters curl -X GET https://your-domain.com/api/auth/microsoft/me/events \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "query": { "$top": 10, "$orderby": "start/dateTime desc", "$select": "subject,start,end" } }' # Get contacts with filtering curl -X GET https://your-domain.com/api/auth/microsoft/me/contacts \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "query": { "$filter": "startsWith(displayName,'\''J'\'')", "$top": 50 } }' # Get email messages curl -X GET https://your-domain.com/api/auth/microsoft/me/messages \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "query": { "$filter": "isRead eq false", "$top": 5, "$orderby": "receivedDateTime desc" } }' # Get OneDrive info curl -X GET https://your-domain.com/api/auth/microsoft/me/drive \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" # Get primary calendar curl -X GET https://your-domain.com/api/auth/microsoft/me/calendar \ -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" ``` -------------------------------- ### Advanced Query Customization Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md Demonstrates how to use Microsoft Graph OData query parameters for customizing API requests. ```APIDOC ## Advanced Query Customization Use Microsoft Graph OData query parameters to customize your requests: ```typescript // Get only specific user profile fields const profile = await authClient.microsoft.me({ query: { $select: "displayName,mail,jobTitle,department", }, }); // Get latest 5 messages with specific fields const messages = await authClient.microsoft.me.messages({ query: { $top: 5, $select: "subject,from,receivedDateTime,isRead", $orderby: "receivedDateTime desc", }, }); // Get events with filtering const events = await authClient.microsoft.me.events({ query: { $filter: "start/dateTime ge '2024-01-01T00:00:00Z'", $orderby: "start/dateTime", $top: 10, }, }); ``` ### Supported OData Parameters | Parameter | Description | Example | |------------|------------------------------------|---------------------------------| | `$select` | Choose specific fields to return | `"displayName,mail,jobTitle"` | | `$filter` | Filter results based on conditions | `"startsWith(displayName,'J')"` | | `$orderby` | Sort results by properties | `"displayName desc"` | | `$top` | Limit number of results (max 999) | `10` | | `$skip` | Skip results for pagination | `20` | | `$expand` | Include related entities inline | `"manager,directReports"` | | `$search` | Search for specific terms | `"displayName:John"` | | `$count` | Include total count in response | `true` | ``` -------------------------------- ### Configure Server-Side Microsoft Graph Plugin Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Set up the Microsoft Graph plugin for the Better Auth server. This involves configuring social provider details like client ID, client secret, and required scopes. It leverages Better Auth's plugin architecture. ```typescript import { betterAuth } from "better-auth"; import { microsoft } from "better-auth-microsoft-graph"; export const auth = betterAuth({ socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID!, clientSecret: process.env.MICROSOFT_CLIENT_SECRET!, prompt: "consent", // Force permission consent flow scopes: [ "User.Read", // User profile access "Calendars.Read", // Calendar and events "Contacts.Read", // Contacts list "Mail.Read", // Email messages "Files.Read", // OneDrive files ], }, }, plugins: [ microsoft({ debugLogs: true, // Enable debug logging (optional) }), ], }); ``` -------------------------------- ### Configure Microsoft Graph Authentication with Better Auth Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md Sets up authentication for Microsoft Graph using Better Auth, specifying client ID, client secret, and desired API scopes. It also enables debug logging for the Microsoft provider. ```typescript export const auth = betterAuth({ socialProviders: { microsoft: { clientId: process.env.MICROSOFT_CLIENT_ID!, clientSecret: process.env.MICROSOFT_CLIENT_SECRET!, prompt: "consent", // Force permission consent flow scopes: [ "User.Read", "Calendars.Read", "Contacts.Read", "Mail.Read", "Files.Read", // Add more scopes as needed. Only add the permissions you need. ], }, }, plugins: [ microsoft({ debugLogs: true, // Enable debug logging }), ], }); ``` -------------------------------- ### Add Microsoft Client Plugin for Better Auth Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md This code demonstrates how to add the Microsoft client plugin to create an authentication client using Better Auth. This plugin is essential for client-side interactions with Microsoft Graph APIs after the server-side authentication is established. ```typescript import { createAuthClient } from "better-auth/react"; import { microsoftClient } from "better-auth-microsoft-graph/client"; const authClient = createAuthClient({ plugins: [microsoftClient()], }); ``` -------------------------------- ### Microsoft Graph Endpoints Source: https://github.com/zpg6/better-auth-microsoft-graph/blob/main/README.md This section details the available Microsoft Graph API endpoints for retrieving user information and data. ```APIDOC ## GET /api/auth/microsoft/me ### Description Retrieves the current user's profile information from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Request Example ```json { "query": { "$select": "displayName,mail" } } ``` ### Response #### Success Response (200) - **displayName** (string) - The user's display name. - **mail** (string) - The user's email address. #### Response Example ```json { "displayName": "Jane Doe", "mail": "jane.doe@example.com" } ``` ## GET /api/auth/microsoft/me/calendar ### Description Retrieves the current user's primary calendar information from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me/calendar ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Response #### Success Response (200) - **name** (string) - The name of the calendar. - **id** (string) - The ID of the calendar. #### Response Example ```json { "name": "Calendar", "id": "some-calendar-id" } ``` ## GET /api/auth/microsoft/me/events ### Description Retrieves the current user's calendar events from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me/events ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Request Example ```json { "query": { "$filter": "start/dateTime ge '2024-01-01T00:00:00Z'", "$orderby": "start/dateTime", "$top": 10 } } ``` ### Response #### Success Response (200) - **value** (array) - A list of calendar events. - **subject** (string) - The subject of the event. - **start** (object) - The start time of the event. - **dateTime** (string) - The date and time. - **end** (object) - The end time of the event. - **dateTime** (string) - The date and time. #### Response Example ```json { "value": [ { "subject": "Team Meeting", "start": {"dateTime": "2024-07-20T10:00:00"}, "end": {"dateTime": "2024-07-20T11:00:00"} } ] } ``` ## GET /api/auth/microsoft/me/contacts ### Description Retrieves the current user's contacts from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me/contacts ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Response #### Success Response (200) - **value** (array) - A list of contacts. - **displayName** (string) - The display name of the contact. - **emailAddresses** (array) - A list of email addresses for the contact. - **address** (string) - The email address. #### Response Example ```json { "value": [ { "displayName": "John Smith", "emailAddresses": [ {"address": "john.smith@example.com"} ] } ] } ``` ## GET /api/auth/microsoft/me/messages ### Description Retrieves the current user's email messages from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me/messages ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Request Example ```json { "query": { "$top": 5, "$select": "subject,from,receivedDateTime,isRead", "$orderby": "receivedDateTime desc" } } ``` ### Response #### Success Response (200) - **value** (array) - A list of email messages. - **subject** (string) - The subject of the message. - **from** (object) - Information about the sender. - **emailAddress** (string) - The sender's email address. - **receivedDateTime** (string) - The date and time the message was received. - **isRead** (boolean) - Whether the message has been read. #### Response Example ```json { "value": [ { "subject": "Project Update", "from": {"emailAddress": "sender@example.com"}, "receivedDateTime": "2024-07-19T09:00:00Z", "isRead": false } ] } ``` ## GET /api/auth/microsoft/me/drive ### Description Retrieves the current user's OneDrive information from Microsoft Graph. ### Method GET ### Endpoint /api/auth/microsoft/me/drive ### Parameters #### Query Parameters - **query** (object) - Optional - OData query parameters for customization. ### Response #### Success Response (200) - **id** (string) - The ID of the user's OneDrive drive. - **driveType** (string) - The type of the drive (e.g., "personal"). #### Response Example ```json { "id": "user-drive-id", "driveType": "personal" } ``` ``` -------------------------------- ### Fetch User Email Messages with Sorting and Pagination Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt This snippet illustrates how to fetch a user's email messages from Microsoft Graph API. It demonstrates retrieving the latest unread emails, sorting messages by received date, and selecting specific message properties like subject, sender, and importance. It also shows fetching important emails. ```typescript import authClient from "./authClient"; async function getEmailMessages() { // Get latest 5 unread emails const messages = await authClient.microsoft.me.messages({ query: { $filter: "isRead eq false", $top: 5, $select: "subject,from,receivedDateTime,bodyPreview,importance", $orderby: "receivedDateTime desc", }, }); if (messages.data?.data) { messages.data.data.forEach(msg => { console.log(`Subject: ${msg.subject}`); console.log(`From: ${msg.from?.emailAddress?.name}`); console.log(`Date: ${msg.receivedDateTime}`); console.log(`Preview: ${msg.bodyPreview?.substring(0, 100)}...`); }); } // Get important emails from specific sender const importantMails = await authClient.microsoft.me.messages({ query: { $filter: "importance eq 'high'", $orderby: "receivedDateTime desc", $top: 10, }, }); console.log(`Important emails: ${importantMails.data?.data?.length || 0}`); } ``` -------------------------------- ### Retrieve User's OneDrive Storage Information Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt This snippet shows how to access a user's OneDrive storage details using the Microsoft Graph API. It retrieves information about the drive, including its ID, type, owner, and quota. The code also calculates and displays the used, total, and remaining storage in gigabytes. ```typescript import authClient from "./authClient"; async function getOneDriveInfo() { const drive = await authClient.microsoft.me.drive({ query: { $select: "id,driveType,owner,quota", }, }); if (drive.data?.data) { const quota = drive.data.data.quota; console.log("Drive ID:", drive.data.data.id); console.log("Drive type:", drive.data.data.driveType); console.log("Owner:", drive.data.data.owner?.user?.displayName); if (quota) { const usedGB = ((quota.used || 0) / (1024 ** 3)).toFixed(2); const totalGB = ((quota.total || 0) / (1024 ** 3)).toFixed(2); const remainingGB = ((quota.remaining || 0) / (1024 ** 3)).toFixed(2); console.log(`Storage used: ${usedGB} GB`); console.log(`Total storage: ${totalGB} GB`); console.log(`Remaining: ${remainingGB} GB`); console.log(`Usage: ${((quota.used || 0) / (quota.total || 1) * 100).toFixed(1)}%`); } } } ``` -------------------------------- ### Access User Profile Data via Microsoft Graph Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Retrieve authenticated user's Microsoft profile information using the Better Auth client. Supports fetching basic profile details or specific fields using OData $select queries and includes error handling. ```typescript import authClient from "./authClient"; async function getUserProfile() { // Basic profile fetch const profile = await authClient.microsoft.me(); if (profile.data?.data) { console.log("Name:", profile.data.data.displayName); console.log("Email:", profile.data.data.mail); console.log("Job Title:", profile.data.data.jobTitle); } // Fetch specific fields only const limitedProfile = await authClient.microsoft.me({ query: { $select: "displayName,mail,jobTitle,department,mobilePhone", }, }); if (limitedProfile.data?.data) { console.log("Department:", limitedProfile.data.data.department); console.log("Phone:", limitedProfile.data.data.mobilePhone); } // Error handling if (!profile.data?.success) { console.error("Error:", profile.data?.error?.message); console.error("Error code:", profile.data?.error?.code); } } ``` -------------------------------- ### Advanced Filtering with Microsoft Graph (TypeScript) Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Demonstrates advanced filtering of Microsoft Graph data using OData query operators for emails, events, and contacts. It utilizes the authClient for making requests and assumes necessary authentication is handled. ```typescript import authClient from "./authClient"; async function advancedFiltering() { // Search emails by keyword const searchResults = await authClient.microsoft.me.messages({ query: { $search: "project update", $top: 20, $orderby: "receivedDateTime desc", }, }); // Filter events by multiple conditions const workEvents = await authClient.microsoft.me.events({ query: { $filter: "start/dateTime ge '2025-10-15T00:00:00Z' and contains(subject,'meeting')", $select: "subject,start,attendees", $orderby: "start/dateTime asc", }, }); // Get contacts with specific criteria const businessContacts = await authClient.microsoft.me.contacts({ query: { $filter: "businessPhones/any()", $select: "displayName,businessPhones,companyName", $orderby: "companyName asc", }, }); console.log(`Search results: ${searchResults.data?.data?.length || 0}`); console.log(`Work events: ${workEvents.data?.data?.length || 0}`); console.log(`Business contacts: ${businessContacts.data?.data?.length || 0}`); } ``` -------------------------------- ### Retrieve Calendar Events with Microsoft Graph Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Fetch user's calendar events using the Better Auth client. Supports filtering, sorting, and selecting specific event fields via OData query parameters like $top, $orderby, and $filter. ```typescript import authClient from "./authClient"; async function getCalendarEvents() { // Get latest 10 events const events = await authClient.microsoft.me.events({ query: { $top: 10, $orderby: "start/dateTime desc", $select: "subject,start,end,location,organizer,attendees", }, }); if (events.data?.data) { events.data.data.forEach(event => { console.log(`Event: ${event.subject}`); console.log(`Start: ${event.start?.dateTime}`); console.log(`Location: ${event.location?.displayName}`); }); } // Get events from specific date range const futureEvents = await authClient.microsoft.me.events({ query: { $filter: "start/dateTime ge '2025-10-15T00:00:00Z'", $orderby: "start/dateTime asc", $top: 20, }, }); console.log(`Upcoming events: ${futureEvents.data?.data?.length || 0}`); } ``` -------------------------------- ### Robust Error Handling for Microsoft Graph (TypeScript) Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Implements comprehensive error handling for Microsoft Graph requests within a try-catch block. It checks for various error codes like 'ACCOUNT_NOT_FOUND', 'TOKEN_EXPIRED', and 'GRAPH_API_ERROR', providing specific console messages and suggestions for handling. ```typescript import authClient from "./authClient"; async function robustErrorHandling() { try { const profile = await authClient.microsoft.me(); if (!profile.data) { console.error("No response data received"); return; } if (!profile.data.success) { const errorCode = profile.data.error?.code; const errorMessage = profile.data.error?.message; switch (errorCode) { case "ACCOUNT_NOT_FOUND": console.error("Microsoft account not linked to user"); // Prompt user to connect Microsoft account break; case "NO_ACCESS_TOKEN": console.error("No access token found"); // Redirect to login break; case "TOKEN_EXPIRED": console.error("Token expired, re-authentication needed"); // Trigger re-authentication flow break; case "INVALID_SCOPES": console.error("Missing required permissions"); // Show permission consent screen break; case "GRAPH_API_ERROR": console.error("Microsoft Graph API error:", errorMessage); break; case "NETWORK_ERROR": console.error("Network error:", errorMessage); // Retry logic break; default: console.error("Unknown error:", errorMessage); } return; } // Success - process data console.log("User profile:", profile.data.data); } catch (error) { console.error("Unexpected error:", error); } } ``` -------------------------------- ### Access Primary Calendar Details via Microsoft Graph Source: https://context7.com/zpg6/better-auth-microsoft-graph/llms.txt Retrieve details of the user's primary calendar using the Better Auth client. Allows selection of specific calendar properties like name, owner, and permissions using OData $select. ```typescript import authClient from "./authClient"; async function getPrimaryCalendar() { const calendar = await authClient.microsoft.me.calendar({ query: { $select: "name,owner,canEdit,canShare,canViewPrivateItems", }, }); if (calendar.data?.data) { console.log("Calendar name:", calendar.data.data.name); console.log("Owner:", calendar.data.data.owner?.name); console.log("Can edit:", calendar.data.data.canEdit); console.log("Can share:", calendar.data.data.canShare); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.