### Run AWS Lambda Example Setup Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Initiates an interactive setup process for the AWS Lambda example, guiding through prerequisites, configuration, and optional deployment. ```bash npm run setup ``` -------------------------------- ### Install Dependencies and Run Messages Example Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/messages/ENVIRONMENT.md Navigate to the examples directory, install npm dependencies, and run the messages example. This assumes environment variables are already configured. ```bash cd examples npm install npm run messages ``` -------------------------------- ### Install Dependencies Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/calendars/README.md Install project dependencies from the examples directory using npm. ```bash cd examples npm install ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/edge-environment/README.md Navigate to the example directory and install project dependencies using npm. Ensure Node.js version 16 or higher is installed. ```bash cd examples/edge-environment npm install ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cjs-only/README.md Run this command in the example directory to install project dependencies. ```bash cd examples/cjs-only npm install ``` -------------------------------- ### Navigate to Example Directory Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Change your current directory to the example project. ```bash cd examples/cloudflare-vite-calendars ``` -------------------------------- ### Run Interactive Setup CLI Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Navigate to the aws-lambda directory and run the interactive setup script for an easy start. This script checks prerequisites, guides through Nylas and AWS credential setup, creates a .env file, and optionally deploys to AWS Lambda. ```bash cd examples/aws-lambda npm run setup ``` -------------------------------- ### Install Dependencies and Setup Environment Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Install project dependencies and copy the environment file. Set the required Nylas API key and URI. ```bash npm install cp .env.example .env ``` ```bash NYLAS_API_KEY=your_nylas_api_key_here NYLAS_API_URI=https://api.us.nylas.com ``` -------------------------------- ### Install AWS Lambda Dependencies and Deploy Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Installs dependencies, configures environment variables, and deploys the AWS Lambda example. ```bash npm install # Create .env file with your Nylas credentials # Configure AWS credentials npm run deploy ``` -------------------------------- ### Run the CommonJS Example Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cjs-only/README.md Execute the main example file using Node.js. ```bash npm start # or node index.js ``` -------------------------------- ### Start Development Server Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Run the development server using npm. The server will start on http://localhost:5173 or another available port. ```bash npm run dev ``` -------------------------------- ### Install and Initialize Nylas SDK Source: https://context7.com/nylas/nylas-nodejs/llms.txt Install the SDK using npm and initialize a Nylas instance with your API key. Configure optional parameters like API URI, timeout, and custom headers. Includes an example of error handling for various Nylas-specific errors. ```typescript npm install nylas import Nylas from 'nylas'; import { NylasApiError, NylasOAuthError, NylasSdkTimeoutError } from 'nylas'; // US region (default) const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY!, apiUri: 'https://api.us.nylas.com', // or 'https://api.eu.nylas.com' for EU timeout: 30, // seconds, default is 90 headers: { 'X-Custom-Header': 'value' }, // extra headers on every request }); // CommonJS const Nylas = require('nylas').default; const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY }); // Error handling pattern used throughout the SDK try { const result = await nylas.calendars.list({ identifier: 'user@example.com' }); } catch (err) { if (err instanceof NylasApiError) { // API-level errors (4xx / 5xx from Nylas) console.error(err.statusCode, err.type, err.message); console.error('Request ID:', err.requestId, 'Flow ID:', err.flowId); } else if (err instanceof NylasOAuthError) { // OAuth flow errors console.error(err.error, err.errorDescription, err.errorUri); } else if (err instanceof NylasSdkTimeoutError) { // Request timed out console.error('Timed out after', err.timeout, 'seconds for', err.url); } } ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/README.md Navigate to the project directory and install necessary dependencies using npm. ```bash cd examples/cloudflare-vite-calendars npm install ``` -------------------------------- ### Run Calendar Examples Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/calendars/README.md Execute the calendar examples using npm or directly with ts-node. ```bash # From the examples directory npm run calendars ``` ```bash # Or directly with ts-node npx ts-node calendars/event_with_notetaker.ts ``` -------------------------------- ### Installation and Initialization Source: https://context7.com/nylas/nylas-nodejs/llms.txt Instructions on how to install the Nylas Node.js SDK and initialize a Nylas client instance with your API key. Includes error handling patterns. ```APIDOC ## Installation and Initialization Install the package and create a `Nylas` instance with your API key. ```typescript npm install nylas import Nylas from 'nylas'; import { NylasApiError, NylasOAuthError, NylasSdkTimeoutError } from 'nylas'; // US region (default) const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY!, apiUri: 'https://api.us.nylas.com', // or 'https://api.eu.nylas.com' for EU timeout: 30, // seconds, default is 90 headers: { 'X-Custom-Header': 'value' }, // extra headers on every request }); // CommonJS const Nylas = require('nylas').default; const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY }); // Error handling pattern used throughout the SDK try { const result = await nylas.calendars.list({ identifier: 'user@example.com' }); } catch (err) { if (err instanceof NylasApiError) { // API-level errors (4xx / 5xx from Nylas) console.error(err.statusCode, err.type, err.message); console.error('Request ID:', err.requestId, 'Flow ID:', err.flowId); } else if (err instanceof NylasOAuthError) { // OAuth flow errors console.error(err.error, err.errorDescription, err.errorUri); } else if (err instanceof NylasSdkTimeoutError) { // Request timed out console.error('Timed out after', err.timeout, 'seconds for', err.url); } } ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Install project dependencies by navigating to the aws-lambda directory and running npm install. ```bash cd examples/aws-lambda npm install ``` -------------------------------- ### Install Dependencies Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Install the necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Run Notetaker Example Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/notetakers/README.md Execute the Notetaker example script. You can run it using npm or directly with ts-node. ```bash # From the examples directory npm run notetakers # Or directly with ts-node npx ts-node notetakers/notetaker.ts ``` -------------------------------- ### Copy Environment File Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/calendars/README.md Copy the example environment file to .env for local configuration. ```bash cp .env.example .env # Edit .env with your editor ``` -------------------------------- ### Run Agent Accounts Example (No Agent Account) Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Execute the agent accounts example to exercise Policies, Rules, and Lists, followed by cleanup. This command assumes environment variables are already set. ```bash npm run agent-accounts ``` -------------------------------- ### Install Nylas Skills CLI Source: https://github.com/nylas/nylas-nodejs/blob/main/README.md Add the Nylas skills to your AI agent environment using npx or install the Nylas CLI for MCP server setup. ```bash npx skills add nylas/skills ``` ```bash /plugin marketplace add nylas/skills # Claude Code ``` ```bash brew install nylas/nylas-cli/nylas ``` ```bash nylas mcp install ``` -------------------------------- ### Run Node.js Examples with ts-node Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Executes Node.js examples using ts-node, demonstrating various SDK functionalities. ```bash npx ts-node grants/grants.ts npx ts-node notetakers/notetaker.ts npx ts-node calendars/event_with_notetaker.ts npx ts-node messages/messages.ts ``` -------------------------------- ### Run Node.js Examples with npm Scripts Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Executes Node.js examples using npm scripts, providing convenient aliases for common tasks. ```bash npm run grants npm run notetakers npm run calendars npm run messages npm run agent-accounts ``` -------------------------------- ### Run Agent Accounts Example (Existing Agent Account) Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Execute the agent accounts example with an existing Agent Account grant ID. Set the AGENT_ACCOUNT_GRANT_ID environment variable before running. ```bash AGENT_ACCOUNT_GRANT_ID=your_agent_account_grant_id ``` ```bash npm run agent-accounts ``` -------------------------------- ### Build and Run Compiled Node.js Examples Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Builds the TypeScript examples into JavaScript and then runs them, useful after compilation. ```bash npm run build node dist/grants/grants.js node dist/notetakers/notetaker.js node dist/calendars/event_with_notetaker.js node dist/messages/messages.js node dist/agent-accounts/agent-accounts.js ``` -------------------------------- ### Configure Node.js Environment Variables Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Copies the example environment file and instructs to fill in API key and other necessary variables. ```bash cp .env.example .env # Edit .env with your editor and add your API key ``` -------------------------------- ### Install Nylas Node SDK v7.0 (Beta) Source: https://github.com/nylas/nylas-nodejs/blob/main/UPGRADE.md Install the beta version of the Nylas Node SDK using npm or yarn. Ensure your Node.js version is at least v16. ```bash npm install nylas@beta ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Copy the example environment file and edit it with your Nylas API key, grant ID, and calendar ID. ```bash # Copy the example file cp .dev.vars.example .dev.vars # Edit .dev.vars with your credentials # You'll need: # - NYLAS_API_KEY: From Nylas Dashboard > Applications # - NYLAS_GRANT_ID: From Nylas Dashboard > Grants # - NYLAS_CALENDAR_ID: Get by calling GET /v3/grants/{grantId}/calendars ``` -------------------------------- ### Serverless Framework Configuration Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Example configuration for a Serverless Framework `serverless.yml` file. Adjust memory, timeout, runtime, and region settings as needed for your Lambda function. ```yaml provider: memorySize: 1024 # Increase for larger files timeout: 60 # Increase timeout region: eu-west-1 # Change region ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/README.md Copy the example environment variables file and update it with your Nylas API key, URI, Grant ID, and Calendar ID. ```bash cp .dev.vars.example .dev.vars NYLAS_API_KEY=your_nylas_api_key_here NYLAS_API_URI=https://api.us.nylas.com NYLAS_GRANT_ID=your_grant_id_here NYLAS_CALENDAR_ID=your_calendar_id_here ``` -------------------------------- ### Set Up Environment Variables (.env file) Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/messages/ENVIRONMENT.md Configure required and optional environment variables in a .env file for the Nylas messages example. Ensure NYLAS_API_KEY and NYLAS_GRANT_ID are set. ```bash # Required NYLAS_API_KEY=your_api_key_here NYLAS_GRANT_ID=your_grant_id_here # Optional NYLAS_API_URI=https://api.us.nylas.com # For testing message sending (optional) TEST_EMAIL=your-test-email@example.com ``` -------------------------------- ### CommonJS Nylas SDK Initialization and Message Listing Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cjs-only/README.md This example demonstrates loading environment variables with `dotenv`, initializing the Nylas client, and listing messages using CommonJS syntax. ```javascript const dotenv = require('dotenv'); const path = require('path'); const Nylas = require('nylas'); // Load environment variables from .env file dotenv.config({ path: path.resolve(__dirname, '../.env'), }); // Initialize the Nylas client const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY, }); // Get the grant ID from environment variables const grantId = process.env.NYLAS_GRANT_ID; async function listMessages() { if (!grantId) { throw new Error('NYLAS_GRANT_ID environment variable is not set.'); } try { // List messages for the grant const messages = await nylas.messages.list({ identifier: grantId, query: { limit: 5, }, }); console.log('Messages:', messages.data); return messages.data; } catch (error) { console.error('Error listing messages:', error.message); throw error; } } // Execute the function and handle potential errors listMessages().catch((error) => { console.error('Example failed:', error); process.exit(1); }); ``` -------------------------------- ### Configure Cloudflare Workers Environment Variables Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/README.md Copies the example development variables file and instructs to edit it with Nylas credentials. ```bash cp .dev.vars.example .dev.vars # Edit .dev.vars with your Nylas credentials ``` -------------------------------- ### Build Manual Deployment Package Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Command to build a deployment package for manual upload to AWS Lambda. This script installs production dependencies and bundles the code using esbuild. ```bash npm run build:manual ``` -------------------------------- ### Install Nylas Node.js SDK Source: https://github.com/nylas/nylas-nodejs/blob/main/README.md Install the Nylas SDK using npm or yarn. Node.js v18 or later is required. The package includes TypeScript types and supports both ESM and CommonJS. ```bash npm install nylas # or yarn add nylas ``` -------------------------------- ### List Calendars with Query Parameters Source: https://github.com/nylas/nylas-nodejs/blob/main/UPGRADE.md Use query parameters to filter or pass additional information when listing resources. This example demonstrates limiting the number of calendars returned. ```typescript import Nylas from "nylas"; import { NylasListResponse } from "nylas/lib/types/models/responses"; import { Calendar, ListCalendersQueryParams } from "nylas/lib/types/models/calendars"; const nylas = new Nylas({ apiKey: "NYLAS_API_KEY", }); const queryParams: ListCalendersQueryParams = { limit: 10 } const response: NylasListResponse = await nylas.calendars.list({ identifier: "GRANT_ID", queryParams, // Now you will get a maximum of 10 calendars back }); ``` -------------------------------- ### Skip Cleanup for Agent Account Resources Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Prevent the example from cleaning up created resources, including the Agent Account grant, Policy, Rule, and List. Set AGENT_ACCOUNTS_SKIP_CLEANUP to true to keep all resources. ```bash AGENT_ACCOUNTS_SKIP_CLEANUP=true ``` -------------------------------- ### Control Agent Account Grant Cleanup Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Configure whether to delete the created Agent Account grant after the example runs. Set AGENT_ACCOUNTS_DELETE_CREATED_GRANT to true to delete the grant. ```bash AGENT_ACCOUNTS_DELETE_CREATED_GRANT=true ``` -------------------------------- ### Create Agent Account Configuration Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/agent-accounts/README.md Configure the creation of a new Agent Account by setting the agent's email address. Optionally enable IMAP/SMTP access with an app password. ```bash AGENT_ACCOUNT_EMAIL=agent@your-registered-domain.com ``` ```bash AGENT_ACCOUNT_APP_PASSWORD=YourSecurePassword123 ``` -------------------------------- ### Get Calendar ID using cURL Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Use cURL to fetch your Calendar ID from the Nylas API. Replace placeholders with your actual credentials. ```bash # Replace with your actual values curl -X GET "https://api.us.nylas.com/v3/grants/YOUR_GRANT_ID/calendars" \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### Deploy to Production Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/QUICKSTART.md Set production secrets using Wrangler and deploy the application. ```bash # Set production secrets wrangler secret put NYLAS_API_KEY wrangler secret put NYLAS_GRANT_ID wrangler secret put NYLAS_CALENDAR_ID # Deploy npm run deploy ``` -------------------------------- ### Get Nylas Outbound IP Addresses Source: https://context7.com/nylas/nylas-nodejs/llms.txt Retrieves a list of Nylas's outbound IP addresses, which can be used for firewall allow-listing to ensure secure communication. ```typescript // Get Nylas outbound IP addresses (for firewall allow-listing) const { data: ips } = await nylas.webhooks.ipAddresses(); console.log(ips.ipAddresses); ``` -------------------------------- ### Handle Nylas HTTP Challenge for Webhook Registration Source: https://context7.com/nylas/nylas-nodejs/llms.txt An Express.js example for handling the HTTP challenge request from Nylas during webhook registration. This ensures the webhook endpoint is verified. ```typescript // Handle the Nylas HTTP challenge during webhook registration (Express example) app.get('/webhooks/nylas', (req, res) => { try { const challenge = nylas.webhooks.extractChallengeParameter(req.url); res.send(challenge); } catch { res.status(400).send('No challenge parameter'); } }); ``` -------------------------------- ### Manage Connector Credentials Source: https://context7.com/nylas/nylas-nodejs/llms.txt Demonstrates how to create credentials for a connector, specifically using a service account for Microsoft. ```typescript // Manage credentials via nylas.connectors.credentials const { data: cred } = await nylas.connectors.credentials.create({ provider: 'microsoft', requestBody: { name: 'Service Account', credentialType: 'service_account', credentialData: { private_key_id: '...', private_key: '...', client_email: '...' }, }, }); ``` -------------------------------- ### Configure AWS Credentials using AWS CLI Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Set up your AWS credentials by running the 'aws configure' command. This is the recommended method for configuring AWS access. ```bash aws configure ``` -------------------------------- ### Initialize Nylas SDK Source: https://github.com/nylas/nylas-nodejs/blob/main/README.md Initialize the Nylas SDK with your API key and optionally an API URI for data residency. A timeout can also be configured in seconds. ```typescript import Nylas from "nylas"; // or: const Nylas = require("nylas").default; const nylas = new Nylas({ apiKey: process.env.NYLAS_API_KEY, apiUri: process.env.NYLAS_API_URI, // e.g. https://api.us.nylas.com timeout: 30, // optional, in seconds }); ``` -------------------------------- ### Add Debug Logging to Handler Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Example of adding custom console logging within your Lambda handler function for debugging purposes. Useful for inspecting file details during uploads. ```typescript console.log('File details:', { count: files.length, totalSize: totalSize, files: files.map(f => ({ name: f.filename, size: f.size })) }); ``` -------------------------------- ### List Folders with Single-Level Hierarchy Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/folders/README.md Demonstrates how to list folders using the `singleLevel` query parameter to retrieve only direct children. ```APIDOC ## List Folders with Single-Level Hierarchy ### Description This operation lists folders, controlling the hierarchy traversal with the `singleLevel` query parameter. When `singleLevel` is `true`, only direct child folders are returned. This is particularly useful for building UI navigation or for performance optimization when only immediate children are needed. This parameter is ignored for non-Microsoft providers. ### Method `POST` (or equivalent SDK method) ### Endpoint `/folders` (conceptual endpoint for listing folders) ### Parameters #### Query Parameters - **identifier** (string) - Required - The grant ID to list folders for. - **singleLevel** (boolean) - Optional - If `true`, retrieves folders from a single-level hierarchy only (direct children). Defaults to `false` (multi-level hierarchy). - **parentId** (string) - Optional - Use the ID of a folder to find all child folders it contains. Can be used in conjunction with `singleLevel`. ### Request Example ```typescript const singleLevelFolders = await nylas.folders.list({ identifier: GRANT_ID, queryParams: { singleLevel: true, }, }); ``` ### Response #### Success Response (200) - **data** (array) - A list of folder objects, potentially filtered by `singleLevel` and `parentId`. - **request_id** (string) - The ID of the request. #### Response Example ```json { "data": [ { "id": "folder-id-child-1", "name": "Subfolder 1", "parent_id": "folder-id-parent", "metadata": {}, "object": "folder" }, { "id": "folder-id-child-2", "name": "Subfolder 2", "parent_id": "folder-id-parent", "metadata": {}, "object": "folder" } ], "request_id": "request-id-def" } ``` ``` -------------------------------- ### Vite with Cloudflare Plugin Workflow Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/README.md These commands are used when developing with Vite and the Cloudflare plugin for Workers. ```bash npm run dev # Vite dev server with Workers support npm run deploy # Vite build + Wrangler deploy ``` -------------------------------- ### Traditional Wrangler Workflow Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/cloudflare-vite-calendars/README.md Use these commands for traditional Wrangler development and deployment. ```bash wrangler dev # Start development wrangler deploy # Deploy ``` -------------------------------- ### List Folders with Hidden Folders (Microsoft Only) Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/folders/README.md Demonstrates how to list all folders, including hidden ones, for Microsoft accounts using the `includeHiddenFolders` parameter. ```APIDOC ## List Folders with Hidden Folders (Microsoft Only) ### Description This operation lists all folders associated with a grant, including hidden system folders when `includeHiddenFolders` is set to `true`. This functionality is specific to Microsoft accounts. ### Method `POST` (or equivalent SDK method) ### Endpoint `/folders` (conceptual endpoint for listing folders) ### Parameters #### Query Parameters - **identifier** (string) - Required - The grant ID to list folders for. - **includeHiddenFolders** (boolean) - Optional - If `true`, includes hidden folders. Defaults to `false`. (Microsoft only) ### Request Example ```typescript const foldersWithHidden = await nylas.folders.list({ identifier: GRANT_ID, queryParams: { includeHiddenFolders: true, }, }); ``` ### Response #### Success Response (200) - **data** (array) - A list of folder objects. - **request_id** (string) - The ID of the request. #### Response Example ```json { "data": [ { "id": "folder-id-1", "name": "Inbox", "parent_id": null, "metadata": {}, "object": "folder" }, { "id": "folder-id-2", "name": "Deleted Items", "parent_id": null, "metadata": {}, "object": "folder" } ], "request_id": "request-id-abc" } ``` ``` -------------------------------- ### List Folders with Nylas Node.js SDK Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/folders/README.md Use this snippet to list folders associated with a grant. Specify `singleLevel: true` to get only direct children, or omit it (or set to `false`) to retrieve all descendants. Ensure you have initialized the Nylas SDK with your API key. ```typescript import Nylas from 'nylas'; const nylas = new Nylas({ apiKey: 'your-api-key' }); // Get only direct children of a specific folder const singleLevelFolders = await nylas.folders.list({ identifier: 'grant-id', queryParams: { parentId: 'parent-folder-id', singleLevel: true } }); // Get all descendants (default behavior) const allFolders = await nylas.folders.list({ identifier: 'grant-id', queryParams: { parentId: 'parent-folder-id', singleLevel: false // or omit this parameter } }); ``` -------------------------------- ### Create, Get Availability, Book, List, and Delete Scheduling Configurations Source: https://context7.com/nylas/nylas-nodejs/llms.txt Manage scheduling pages (configurations) using the Nylas Scheduler API. This includes creating a configuration, checking availability for a time slot, creating a booking, listing all configurations, and deleting a configuration. Ensure the NYLAS_GRANT_ID environment variable is set. ```typescript const GRANT = process.env.NYLAS_GRANT_ID!; // Create a scheduling configuration (booking page) const { data: config } = await nylas.scheduler.configurations.create({ identifier: GRANT, requestBody: { requiresSessionAuth: false, participants: [ { email: 'host@example.com', name: 'Host', availability: { calendarIds: ['primary'] }, bookingCalendarId: 'primary', }, ], availability: { durationMinutes: 30, intervalMinutes: 15 }, eventBooking: { title: '30-min intro call', location: 'Google Meet' }, slug: 'intro-call-host', }, }); console.log('Booking page slug:', config.slug); ``` ```typescript // Get scheduling availability const { data: avail } = await nylas.scheduler.availability.get({ configurationId: config.id, queryParams: { startTime: Math.floor(Date.now() / 1000), endTime: Math.floor(Date.now() / 1000) + 7 * 24 * 3600, }, }); console.log(avail.timeSlots); ``` ```typescript // Create a booking (confirm a time slot) const { data: booking } = await nylas.scheduler.bookings.create({ requestBody: { configurationId: config.id, startTime: 1750000000, endTime: 1750001800, guest: { name: 'Guest User', email: 'guest@example.com' }, }, }); console.log(booking.bookingId, booking.status); ``` ```typescript // List all configurations for await (const page of nylas.scheduler.configurations.list({ identifier: GRANT })) { for (const c of page.data) console.log(c.id, c.slug); } ``` ```typescript // Delete a configuration await nylas.scheduler.configurations.destroy({ identifier: GRANT, configurationId: config.id }); ``` -------------------------------- ### Create, List, Rotate, and Delete Webhooks Source: https://context7.com/nylas/nylas-nodejs/llms.txt Demonstrates creating a webhook destination, storing its secret, listing existing webhooks, rotating the signing secret, and finally deleting the webhook. Ensure the webhook secret is stored securely as it's only returned upon creation. ```typescript const { data: webhook } = await nylas.webhooks.create({ requestBody: { triggerTypes: ['message.created', 'event.created', 'calendar.created'], webhookUrl: 'https://myapp.com/webhooks/nylas', description: 'Production webhook', notificationEmailAddresses: ['ops@myapp.com'], }, }); // Store webhook.webhookSecret securely — it is only returned on create console.log('Webhook secret:', webhook.webhookSecret); ``` ```typescript // List webhooks for await (const page of nylas.webhooks.list()) { for (const wh of page.data) console.log(wh.id, wh.status); } ``` ```typescript // Rotate the signing secret for a webhook const { data: rotated } = await nylas.webhooks.rotateSecret({ webhookId: webhook.id }); console.log('New secret:', rotated.webhookSecret); ``` ```typescript // Delete a webhook await nylas.webhooks.destroy({ webhookId: webhook.id }); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Create a .env file in the aws-lambda directory and populate it with your Nylas API key, API URI, and Grant ID. Ensure these values are correctly obtained from your Nylas Dashboard. ```bash NYLAS_API_KEY=your_nylas_api_key_here NYLAS_API_URI=https://api.us.nylas.com NYLAS_GRANT_ID=your_grant_id_here ``` -------------------------------- ### Manual Pagination with next() Source: https://context7.com/nylas/nylas-nodejs/llms.txt Manually paginate through list responses by fetching pages sequentially using `next()` and `pageToken`. Useful when you need more control over the pagination process. ```typescript // Option 2: Manual pagination using next() const firstPage = await nylas.messages.list({ identifier: GRANT, queryParams: { limit: 10 } }); console.log(firstPage.data); // first 10 messages if (firstPage.nextCursor) { const secondPage = await nylas.messages.list({ identifier: GRANT, queryParams: { limit: 10, pageToken: firstPage.nextCursor }, }); } ``` -------------------------------- ### List Policies and Rules Source: https://context7.com/nylas/nylas-nodejs/llms.txt List all existing policies and rules. These methods support asynchronous iteration over paginated results. ```typescript // List policies and rules for await (const page of nylas.policies.list()) { for (const p of page.data) console.log(p.id, p.name); } for await (const page of nylas.rules.list()) { for (const r of page.data) console.log(r.id, r.name, r.policyId); } ``` -------------------------------- ### Deploy with Custom Domain Route Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/edge-environment/README.md After configuring the route in wrangler.toml, run this command to deploy your worker with the specified custom domain. ```bash wrangler deploy ``` -------------------------------- ### Initialize Nylas SDK with API Key Source: https://github.com/nylas/nylas-nodejs/blob/main/UPGRADE.md Initialize a new instance of the Nylas SDK by passing your API key to the constructor. The SDK is now a hybrid Node project supporting both CommonJS and ES6 modules. ```typescript import Nylas from "nylas"; const nylas = new Nylas({ apiKey: "NYLAS_API_KEY", // Required to make API calls }) ``` -------------------------------- ### View Lambda Logs Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/aws-lambda/README.md Command to view your AWS Lambda function logs in real-time using the Serverless Framework. ```bash npm run logs ``` -------------------------------- ### List Grants with Pagination Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/grants/README.md Handle large numbers of grants efficiently by using pagination. Specify the limit and offset to retrieve grants in chunks. ```typescript // List with pagination const grants = await nylas.grants.list({ queryParams: { limit: 10, offset: 0, }, }); ``` -------------------------------- ### Create Policy Source: https://context7.com/nylas/nylas-nodejs/llms.txt Create a new email routing policy. Policies define actions like forwarding emails to a specified address. ```typescript // Create a policy const { data: policy } = await nylas.policies.create({ requestBody: { name: 'Auto-route support emails', actions: [{ type: 'forward', forwardTo: 'support-team@example.com' }], }, }); ``` -------------------------------- ### List, Send, Update, and Schedule Messages with Nylas Node.js SDK Source: https://context7.com/nylas/nylas-nodejs/llms.txt Demonstrates listing messages with filters, sending a message with attachments, updating message status, scheduling a message for later, and cleaning message content. Ensure the GRANT_ID environment variable is set. ```typescript const GRANT = process.env.NYLAS_GRANT_ID!; // List messages with filters (auto-paginate) for await (const page of nylas.messages.list({ identifier: GRANT, queryParams: { subject: 'Invoice', from: ['vendor@supplier.com'], limit: 25, fields: 'include_tracking_options', }, })) { for (const msg of page.data) { console.log(msg.id, msg.subject, msg.date); } } ``` ```typescript // Send a message (auto-selects multipart/form-data for attachments > 3 MB) const { data: sent } = await nylas.messages.send({ identifier: GRANT, requestBody: { subject: 'Hello from Nylas', body: '

Hi there!

Sent via Nylas SDK.

', to: [{ email: 'recipient@example.com', name: 'Recipient' }], cc: [{ email: 'manager@example.com' }], replyToMessageId: '', trackingOptions: { opens: true, links: true, threadReplies: true }, attachments: [ { filename: 'report.pdf', contentType: 'application/pdf', content: Buffer.from(pdfBytes), }, ], }, }); console.log(sent.id); // message ID on the provider ``` ```typescript // Update a message (mark as read/unread, move to folder) await nylas.messages.update({ identifier: GRANT, messageId: sent.id, requestBody: { unread: false, starred: true, folders: ['INBOX'] }, }); ``` ```typescript // Schedule a message for later sending const { data: scheduled } = await nylas.messages.send({ identifier: GRANT, requestBody: { subject: 'Scheduled newsletter', body: 'Content here', to: [{ email: 'subscriber@example.com' }], sendAt: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now }, }); ``` ```typescript // List / stop scheduled messages const { data: schedules } = await nylas.messages.listScheduledMessages({ identifier: GRANT }); await nylas.messages.stopScheduledMessage({ identifier: GRANT, scheduleId: schedules[0].scheduleId }); ``` ```typescript // Clean message bodies (strip signatures, quoted replies, etc.) const cleaned = await nylas.messages.cleanMessages({ identifier: GRANT, requestBody: { messageId: [sent.id], removeQuotedReply: true, removeEmailSignature: true, imagesAsMarkdown: false, }, }); ``` -------------------------------- ### List Folders with Hidden Folders (Microsoft) Source: https://github.com/nylas/nylas-nodejs/blob/main/examples/folders/README.md Demonstrates how to include hidden folders in the list response for Microsoft accounts using the `includeHiddenFolders` parameter. This parameter defaults to false. ```typescript const foldersWithHidden = await nylas.folders.list({ identifier: GRANT_ID, queryParams: { includeHiddenFolders: true, // Microsoft only - includes hidden folders }, }); ``` -------------------------------- ### List, Find, Create, Update, and Delete Connectors Source: https://context7.com/nylas/nylas-nodejs/llms.txt Manage OAuth provider connectors like Google and Microsoft. This snippet covers listing all connectors, finding a specific one by provider, creating a new connector, updating an existing one, and deleting a connector. ```typescript // List all configured connectors for await (const page of nylas.connectors.list({})) { for (const c of page.data) console.log(c.provider, c.settings); } ``` ```typescript // Find a connector by provider const { data: googleConnector } = await nylas.connectors.find({ provider: 'google' }); ``` ```typescript // Create a connector const { data: connector } = await nylas.connectors.create({ requestBody: { provider: 'google', settings: { clientId: 'google-oauth-client-id', clientSecret: 'google-oauth-client-secret', }, authMethod: 'browser_auth', }, }); ``` ```typescript // Update a connector await nylas.connectors.update({ provider: 'google', requestBody: { settings: { clientId: 'new-client-id', clientSecret: 'new-secret' } }, }); ``` ```typescript // Delete connector await nylas.connectors.destroy({ provider: 'google' }); ``` -------------------------------- ### Pagination Source: https://context7.com/nylas/nylas-nodejs/llms.txt Information on how to paginate through list responses. ```APIDOC ## Pagination All list methods return an `AsyncListResponse` supporting both manual `next()` calls and `for await...of` auto-pagination. ### Auto-pagination with `for await...of` This is the recommended way to iterate through all pages of a list. ```typescript const GRANT = process.env.NYLAS_GRANT_ID!; for await (const page of nylas.messages.list({ identifier: GRANT, queryParams: { limit: 50 } })) { for (const msg of page.data) { console.log(msg.id, msg.subject); } // page.nextCursor is available if you need manual control } ``` ### Manual Pagination with `next()` Use this method if you need more control over the pagination process. ```typescript const GRANT = process.env.NYLAS_GRANT_ID!; const firstPage = await nylas.messages.list({ identifier: GRANT, queryParams: { limit: 10 } }); console.log(firstPage.data); // first 10 messages if (firstPage.nextCursor) { const secondPage = await nylas.messages.list({ identifier: GRANT, queryParams: { limit: 10, pageToken: firstPage.nextCursor }, }); console.log(secondPage.data); // next 10 messages } ``` ```