This example demonstrates how to use the Nylas Node.js SDK in a pure CommonJS (CJS) environment without ES module syntax.
- Shows CommonJS
require()syntax with the Nylas SDK - Demonstrates environment variable handling in CommonJS
- Provides a simple messages listing example
- Serves as a reference for projects that must use CommonJS
This example showcases the CommonJS equivalent of the ESM-only example:
| ESM Syntax | CommonJS Syntax |
|---|---|
import Nylas from 'nylas' |
const Nylas = require('nylas') |
import dotenv from 'dotenv' |
const dotenv = require('dotenv') |
import path from 'node:path' |
const path = require('path') |
import.meta.dirname |
__dirname |
export { logger } |
module.exports = { logger } |
-
Install dependencies:
cd examples/cjs-only npm install -
Set up environment variables:
- Copy
examples/.env.exampletoexamples/.env - Fill in your
NYLAS_API_KEYandNYLAS_GRANT_ID
- Copy
-
Run the example:
npm start # or node index.js
- Node.js (any version - CommonJS is supported in all Node.js versions)
- Valid Nylas API credentials
- A grant with message access permissions
- Loads environment variables using
dotenv - Validates required API credentials
- Initializes the Nylas client
- Lists messages from the specified grant
- Logs the results with proper error handling
cjs-only/
├── index.js # Main example file (CommonJS)
├── package.json # Package configuration (no "type": "module")
├── utils/
│ └── logger.js # Logger utility (CommonJS exports)
└── README.md # This file
- "NYLAS_API_KEY environment variable is not set": Make sure you've created the
.envfile in theexamples/directory with your API key - "NYLAS_GRANT_ID environment variable is not set": Add your grant ID to the
.envfile - Module not found errors: Run
npm installto install dependencies - Permission errors: Ensure your API key and grant have the necessary permissions to list messages
../esm-only/- ESM version of this same example../messages/- More comprehensive message handling examples