### Run Example Application Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Execute any of the provided example scripts using Node.js. Ensure you have the necessary credentials configured. ```bash node examples/create-credentials.js ``` -------------------------------- ### Example Proxy Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md An example of how to structure the request configuration object with proxy details, including authentication. ```typescript const config = { path: '/api/endpoint', method: 'GET', proxy: { host: 'proxy.example.com', port: 3128, protocol: 'http', auth: { username: 'proxyuser', password: 'proxypass' } } }; ``` -------------------------------- ### Make a GET Request Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Perform a GET request to an API endpoint. This example shows how to specify the path, method, and headers for the request. ```javascript eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET', headers: { 'Accept': 'application/json' } }).send((error, response, body) => { if (error) { console.error('Request failed:', error); } else { console.log('Success! Response:', body); } }); ``` -------------------------------- ### .edgerc File Configuration Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md An example of the structure and required fields for the .edgerc configuration file, used for storing Akamai API credentials. ```ini [default] client_token = akab-... client_secret = ...= access_token = akab-... host = akab-...luna.akamaiapis.net ``` -------------------------------- ### Complete Akamai API Request Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Demonstrates how to initialize the EdgeGrid client, authenticate, and send a GET request to the Akamai API to retrieve identity management credentials. Includes error handling and promise-based resolution. ```javascript const EdgeGrid = require('akamai-edgegrid'); async function getCredentials() { const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); return new Promise((resolve, reject) => { eg.auth({ path: '/identity-management/v3/api-clients/self/credentials', method: 'GET', headers: { 'Accept': 'application/json' } }).send((error, response, body) => { if (error) { reject(error); } else { resolve(JSON.parse(body)); } }); }); } // Usage getCredentials() .then(credentials => { console.log('Your credentials:', credentials); }) .catch(error => { console.error('Failed to fetch credentials:', error.message); process.exit(1); }); ``` -------------------------------- ### Send Method Callback Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md An example demonstrating how to use the `SendCallback` with the `eg.send` method. It includes error handling and logging of response details. ```typescript eg.send((error, response, body) => { if (error) { console.error('Request failed:', error.message); return; } console.log('Status:', response.status); console.log('Headers:', response.headers); console.log('Body:', body); }); ``` -------------------------------- ### Authentication Flow Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Demonstrates the typical three-step authentication flow using the EdgeGrid client: initialization, request signing, and sending the request. ```javascript 1. new EdgeGrid(options) // Initialize with credentials 2. eg.auth({ path: '...', ... }) // Prepare and sign request 3. eg.send((error, response) => {}) // Execute and handle response ``` -------------------------------- ### Install Akamai EdgeGrid Node.js Library Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Install the library using npm. This is the first step to using EdgeGrid authentication in your Node.js project. ```bash npm install akamai-edgegrid ``` -------------------------------- ### Basic GET Request with EdgeGrid Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Demonstrates how to initialize EdgeGrid and make a basic GET request to an API endpoint. Ensure the '~/.edgerc' file is correctly configured. ```javascript const eg = new EdgeGrid({ path: '~/.edgerc' }); eg.auth({ path: '/api/endpoint', method: 'GET' }).send((error, response, body) => { if (error) console.error(error); else console.log(body); }); ``` -------------------------------- ### Example .edgerc File with Multiple Sections Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Illustrates a complete .edgerc file with multiple credential sections for different environments (default, production, staging), including comments and optional properties. ```ini ; Akamai API credentials [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net [production] client_token = akab-prod-token-xxx client_secret = prod-secret-xxx= access_token = akab-prod-access-xxx host = https://akab-prod-host-xxx.luna.akamaiapis.net max-body = 262144 [staging] client_token = akab-stage-token-xxx client_secret = stage-secret-xxx= access_token = akab-stage-access-xxx host = akab-stage-host-xxx.luna.akamaiapis.net ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Illustrates how to include query parameters in a GET request using the 'qs' option. This is useful for filtering or specifying request details. ```javascript eg.auth({ path: '/api/endpoint', method: 'GET', qs: { param1: 'value1', param2: 'value2' } }).send((error, response, body) => { // Handle response }); ``` -------------------------------- ### Handle EdgeGrid Configuration Errors Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md This example demonstrates how to catch and log errors that occur during EdgeGrid client initialization due to invalid configuration, such as a missing .edgerc file. ```javascript try { const eg = new EdgeGrid({ path: '/nonexistent/.edgerc', section: 'default' }); } catch (error) { console.error('Configuration error:', error.message); } ``` -------------------------------- ### Enable Logging in Code Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This example shows how to enable logging directly within your JavaScript code by setting environment variables and calling `enableLogging`. ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); // Enable debug logging process.env.AKAMAI_LOG_LEVEL = 'debug'; process.env.AKAMAI_LOG_PRETTY = 'true'; eg.enableLogging(true); ``` -------------------------------- ### Pretty Log Output Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This is an example of the human-readable, pretty-printed log output format when enabled. It displays time, level, and message with indented details. ```text [14:32:45.123] INFO: Signed authorization header signedAuthHeader: "EG1-HMAC-SHA256..." ``` -------------------------------- ### Example .edgerc File Structure Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/edgerc.md Demonstrates the INI format for the .edgerc file, showing different sections like 'default', 'production', and 'staging' with their respective credentials and host configurations. Supports comments and optional properties like max-body. ```ini [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net [production] client_token = akab-prod-token-xxx client_secret = prod-secret-xxx= access_token = akab-prod-access-xxx host = akab-prod-host-xxx.luna.akamaiapis.net max-body = 262144 [staging] client_token = akab-stage-token-xxx client_secret = stage-secret-xxx= access_token = akab-stage-access-xxx host = https://akab-stage-host-xxx.luna.akamaiapis.net ``` -------------------------------- ### Custom Logger with Bunyan Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This example demonstrates how to integrate with Bunyan for custom logging. It shows creating a Bunyan logger and wrapping it to be compatible with the `enableLogging` method. ```javascript const bunyan = require('bunyan'); const log = bunyan.createLogger({ name: 'akamai-edgegrid' }); const wrappedLogger = { info: (obj, msg) => log.info(obj, msg), debug: (obj, msg) => log.debug(obj, msg), error: (obj, msg) => log.error(obj, msg), warn: (obj, msg) => log.warn(obj, msg) }; const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); eg.enableLogging(wrappedLogger); ``` -------------------------------- ### Make a PUT Request Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Perform a PUT request to update a resource. This example demonstrates sending updated data in the request body. ```javascript eg.auth({ path: '/identity-management/v3/user-profile/basic-info', method: 'PUT', headers: { 'Accept': 'application/json' }, body: { firstName: 'John', lastName: 'Smith', timeZone: 'America/New_York' } }).send((error, response, body) => { console.log(body); }); ``` -------------------------------- ### Fetch User Profile with EdgeGrid Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Demonstrates how to initialize the EdgeGrid client and make an authenticated GET request to retrieve a user profile. Ensure your .edgerc file is configured correctly. ```typescript import EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); interface UserProfile { email: string; firstName: string; lastName: string; } eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET', headers: { 'Accept': 'application/json' } }).send((error, response, body) => { if (error) { console.error('Request failed:', error); return; } const profile: UserProfile = JSON.parse(body); console.log(`Hello ${profile.firstName} ${profile.lastName}`); }); ``` -------------------------------- ### Custom Logger with Winston Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Integrate the akamai-edgegrid-node library with Winston for custom logging. This example shows how to create a Winston logger and wrap it to match the expected interface for `enableLogging`. ```javascript const winston = require('winston'); const logger = winston.createLogger({ level: 'debug', format: winston.format.json(), transports: [ new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }) ] }); // Wrap Winston to match the expected interface const wrappedLogger = { info: (obj, msg) => logger.info(msg, obj), debug: (obj, msg) => logger.debug(msg, obj), error: (obj, msg) => logger.error(msg, obj), warn: (obj, msg) => logger.warn(msg, obj) }; const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); eg.enableLogging(wrappedLogger); ``` -------------------------------- ### JSON Log Output Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This is an example of the JSON output format when pretty printing is disabled. It includes log level, timestamp, and the message. ```json {"level":30,"time":"2026-07-09T14:32:45.123Z","msg":"Signed authorization header","signedAuthHeader":"EG1-HMAC-SHA256..."} ``` -------------------------------- ### Request Configuration Object Example Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md An example of the request configuration object used with the `EdgeGrid.prototype.auth(requestOptions)` method. It specifies API endpoint path, HTTP method, headers, body, and query parameters. ```typescript const requestConfig = { path: '/api/endpoint', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { name: 'John', age: 30 }, qs: { filter: 'active' } }; ``` -------------------------------- ### Enable Logging via Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Logging can be enabled by setting environment variables before running the Node.js application. This example shows how to set the log level and enable pretty printing. ```bash # Set environment before running Node export AKAMAI_LOG_LEVEL=info export AKAMAI_LOG_PRETTY=true node app.js ``` -------------------------------- ### Loading Credentials from Environment Variables in Node.js Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/edgerc.md Provides an example of how to export Akamai credentials as environment variables and then load them into a Node.js application using the 'akamai-edgegrid' library. This method is used when the .edgerc file is not available. ```bash export AKAMAI_HOST="akab-h05tnam3...luna.akamaiapis.net" export AKAMAI_CLIENT_TOKEN="akab-c113ntt0k3n..." export AKAMAI_CLIENT_SECRET="C113nt53KR3TN6N90..." export AKAMAI_ACCESS_TOKEN="akab-acc35t0k3n..." ``` ```javascript const edgerc = require('akamai-edgegrid/src/edgerc'); const config = edgerc(); // Loads from AKAMAI_* env vars ``` -------------------------------- ### Set Logging Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Configure logging behavior by exporting environment variables before running your Node.js application. This example sets the log level to debug and enables pretty-printed output. ```bash export AKAMAI_LOG_LEVEL=debug export AKAMAI_LOG_PRETTY=true node app.js ``` -------------------------------- ### EdgeGrid Constructor with File Path Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Demonstrates initializing the EdgeGrid SDK using a path to the .edgerc file and optionally specifying a configuration section. ```javascript new EdgeGrid({ path: '~/.edgerc', section: 'default' }) ``` -------------------------------- ### Initializing EdgeGrid with Multiple Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Demonstrates how to configure and use multiple sets of credentials by specifying different sections from the '.edgerc' file for production and staging environments. ```javascript const prod = new EdgeGrid({ path: '~/.edgerc', section: 'production' }); const stage = new EdgeGrid({ path: '~/.edgerc', section: 'staging' }); ``` -------------------------------- ### Initialize EdgeGrid with Constructor Options Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Instantiate the EdgeGrid client by providing configuration options such as the path to the credentials file, the section to use, and debug mode. ```javascript new EdgeGrid({ path: '~/.edgerc', // Path to credentials file section: 'default', // [section] header in .edgerc debug: false // Deprecated }) ``` -------------------------------- ### Initialize EdgeGrid with Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Set AKAMAI_* environment variables to initialize the EdgeGrid client without specifying a path. This is an alternative to using a .edgerc file. ```bash export AKAMAI_HOST="akab-h05tnam3...luna.akamaiapis.net" export AKAMAI_ACCESS_TOKEN="akab-acc35t0k3n..." export AKAMAI_CLIENT_TOKEN="akab-c113ntt0k3n..." export AKAMAI_CLIENT_SECRET="C113nt53KR3TN6N90..." ``` ```javascript const eg = new EdgeGrid({}); // Loads from AKAMAI_* env vars ``` -------------------------------- ### EdgeGrid Constructor with Direct Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Shows how to initialize the EdgeGrid SDK by passing API credentials directly as arguments, bypassing the need for a .edgerc file. ```javascript new EdgeGrid( clientToken, clientSecret, accessToken, host ) ``` -------------------------------- ### Add Query String Parameters to Request Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Include query string parameters in a GET request. This allows for filtering or specifying options for the API endpoint. ```javascript eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET', qs: { authGrants: true, notifications: true } }).send((error, response, body) => { console.log(body); }); ``` -------------------------------- ### Initialize EdgeGrid with .edgerc file Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Initializes the EdgeGrid client using a path to a .edgerc configuration file and an optional section name. Ensure the .edgerc file exists and contains the necessary credentials. ```javascript new EdgeGrid({ path: string, // Path to .edgerc file (supports ~ for home directory) section?: string, // Section header in .edgerc (default: 'default') debug?: boolean // Deprecated parameter, kept for backwards compatibility }) ``` ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); ``` -------------------------------- ### Send Request with Binary Response Type Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Handles binary responses by setting `responseType` to 'arraybuffer' in the `auth` method and processing the `response.data` in the `send` callback, for example, saving to a file. ```javascript const fs = require('fs'); eg.auth({ path: '/invoicing-api/v2/contracts/123/invoices/456/files/invoice.pdf', method: 'GET', responseType: 'arraybuffer' }).send((err, response) => { if (err) { console.error(err); return; } fs.writeFile('./invoice.pdf', response.data, 'binary', (err) => { if (err) { console.error('File write error:', err); } else { console.log('File saved successfully'); } }); }); ``` -------------------------------- ### Configure EdgeGrid using Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Set Akamai API credentials and logging preferences using environment variables for configuration. ```bash AKAMAI_HOST = "..." AKAMAI_ACCESS_TOKEN = "..." AKAMAI_CLIENT_TOKEN = "..." AKAMAI_CLIENT_SECRET = "..." AKAMAI_LOG_LEVEL = "debug" AKAMAI_LOG_PRETTY = "true" ``` -------------------------------- ### Initialize EdgeGrid Client Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Initialize the EdgeGrid client using either file-based configuration or direct credentials. ```javascript new EdgeGrid({ path: string, section?: string }) ``` ```javascript new EdgeGrid(clientToken: string, clientSecret: string, accessToken: string, host: string) ``` -------------------------------- ### Enable Logging with Defaults Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Enable logging using environment variables AKAMAI_LOG_LEVEL and AKAMAI_LOG_PRETTY to configure verbosity and output format. This is the default behavior when passing `true`. ```javascript const { enableLogging } = require('akamai-edgegrid/src/logger'); enableLogging(true); // Uses AKAMAI_LOG_LEVEL and AKAMAI_LOG_PRETTY env vars ``` -------------------------------- ### Enable Logging via Environment Variables (JavaScript) Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This JavaScript snippet demonstrates how to initialize the EdgeGrid client and then enable logging, which will read the environment variables set for log level and pretty printing. ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); eg.enableLogging(true); // Reads env vars and enables ``` -------------------------------- ### Get and Use Logger Instance Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Retrieve the current logger instance using `getLogger()`. The returned logger object has `info`, `debug`, `error`, and `warn` methods for logging messages and objects. ```javascript const { getLogger } = require('akamai-edgegrid/src/logger'); const logger = getLogger(); logger.info({ key: 'value' }, 'Log message'); logger.debug({ data: 'object' }, 'Debug info'); ``` -------------------------------- ### Handle Invalid Logger Object Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/errors.md This snippet shows how to trigger an error by passing an incomplete logger object to enableLogging and provides a recovery example using a custom logger object that implements all required methods. ```javascript const eg = new EdgeGrid({ path: '~/.edgerc' }); // Invalid logger (missing 'warn' method) eg.enableLogging({ info: () => {}, debug: () => {}, error: () {} // Missing 'warn' }); // Throws: Error: Invalid argument passed to enableLogging... ``` ```javascript const customLogger = { info: (obj, msg) => console.log(`[INFO] ${msg}`, obj), debug: (obj, msg) => console.log(`[DEBUG] ${msg}`, obj), error: (obj, msg) => console.error(`[ERROR] ${msg}`, obj), warn: (obj, msg) => console.warn(`[WARN] ${msg}`, obj) }; const eg = new EdgeGrid({ path: '~/.edgerc' }); eg.enableLogging(customLogger); // Valid ``` -------------------------------- ### EdgeGrid Constructor (from .edgerc file) Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Initializes an EdgeGrid authentication client using a .edgerc configuration file. Supports specifying the path to the file and the section header. ```APIDOC ## EdgeGrid(options) ### Description Initializes an EdgeGrid authentication client using a `.edgerc` configuration file. ### Parameters #### Path Parameters - **path** (string) - Required - File path to `.edgerc` configuration file. Supports `~` notation for home directory expansion. - **section** (string) - Optional - Section header name within the `.edgerc` file containing credentials. Defaults to 'default'. - **debug** (boolean) - Optional - Deprecated parameter, kept for backwards compatibility. Defaults to false. ### Throws `Error` if `.edgerc` file cannot be read, section not found, or credentials are missing. ### Request Example ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); ``` ``` -------------------------------- ### Initialize EdgeGrid with Configuration Object Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md Use this snippet to initialize the EdgeGrid client by providing a configuration object. Specify the path to your `.edgerc` file and optionally the section name. ```typescript const config = { path: '~/.edgerc', section: 'default' }; const eg = new EdgeGrid(config); ``` -------------------------------- ### Handle binary data with responseType arraybuffer Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/README.md When retrieving binary data, such as PDF invoices, specify `responseType: 'arraybuffer'` in the `auth` method to ensure correct handling. The example shows saving the received data to a file. ```javascript const fs = require('fs'); eg.auth({ path : `/invoicing-api/v2/contracts/${contractId}/invoices/${invoiceNumber}/files/${fileName}`, method: 'GET', responseType: 'arraybuffer', // Important }).send((err, response) => { if (err) { return console.log(err); } fs.writeFile(`./${fileName}`, response.data, 'binary', (err) => { if (err){ return console.log(err); } console.log('File was saved!'); }); }); ``` -------------------------------- ### Initialize EdgeGrid Client Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Initialize the EdgeGrid client with the path to your credentials file and the desired section. This sets up the client for making authenticated requests. ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); ``` -------------------------------- ### EdgeGrid Constructor Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md Configuration options for initializing the EdgeGrid client. The `path` to the `.edgerc` file is required, while `section` and `debug` are optional. ```APIDOC ## Configuration Object (Constructor) **Used by:** `new EdgeGrid(configObject)` **Properties:** | Property | Type | Required | Description | |----------|------|----------|-------------| | path | string | Yes | Path to `.edgerc` file (supports `~`) | | section | string | No | Section name in `.edgerc` (default: 'default') | | debug | boolean | No | Deprecated, kept for backwards compatibility | **Example:** ```typescript const config = { path: '~/.edgerc', section: 'default' }; const eg = new EdgeGrid(config); ``` ``` -------------------------------- ### Comprehensive API Request Error Handling Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/errors.md A robust example demonstrating how to initialize the EdgeGrid client with error handling for configuration issues and how to manage potential errors during API requests, including network errors and specific HTTP status codes like 401 and 429. ```javascript const EdgeGrid = require('akamai-edgegrid'); async function makeApiCall(path, method = 'GET') { let eg; // Step 1: Initialize with error handling try { eg = new EdgeGrid({ path: '~/.edgerc', section: process.env.AKAMAI_SECTION || 'default' }); // Validate config if (!eg.config.host || !eg.config.client_token) { throw new Error('Incomplete credentials in .edgerc'); } } catch (error) { console.error('Configuration error:', error.message); throw error; } // Step 2: Make request with error handling return new Promise((resolve, reject) => { eg.auth({ path, method, headers: { 'Accept': 'application/json' } }).send((error, response, body) => { if (error) { if (error.response) { // HTTP error const status = error.response.status; console.error(`HTTP ${status}:`, error.response.statusText); if (status === 401) { reject(new Error('Authentication failed')); } else if (status === 429) { reject(new Error('Rate limited')); } else { reject(error); } } else if (error.code) { // Network error console.error('Network error:', error.code); reject(error); } else { // Unknown error reject(error); } } else { resolve(body); } }); }); } // Usage makeApiCall('/identity-management/v3/user-profile') .then(body => console.log(body)) .catch(error => { console.error('Request failed:', error.message); process.exit(1); }); ``` -------------------------------- ### Configure EdgeGrid with .edgerc file Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/README.md Instantiate the EdgeGrid client using a path to your .edgerc file and the section header for your credentials. ```javascript var eg = new EdgeGrid({ path: '/path/to/.edgerc', section: '' }); ``` -------------------------------- ### Handle HTTP Error Status Codes Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/errors.md This example demonstrates how to check the HTTP status code of an API response error and log specific messages for common codes like 401, 403, 404, and 429. It also includes a default case for other API errors. ```javascript eg.send((error, response) => { if (error && error.response) { switch (error.response.status) { case 401: console.error('Authentication failed - check credentials'); break; case 403: console.error('Access denied - insufficient permissions'); break; case 404: console.error('Endpoint not found'); break; case 429: console.error('Rate limited - wait before retrying'); break; default: console.error(`API error: ${error.response.status} ${error.response.statusText}`); } } }); ``` -------------------------------- ### Auto-Initialization Logic Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md This JavaScript code snippet demonstrates the module's auto-initialization logic for logging. It enables logging based on environment variables unless the environment is set to 'test'. ```javascript if (process.env.EDGEGRID_ENV !== 'test') { if (process.env.AKAMAI_LOG_LEVEL || process.env.AKAMAI_LOG_PRETTY) { enableLogging(true); } } ``` -------------------------------- ### Initialize EdgeGrid with Default Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Instantiate the EdgeGrid client without specifying a section path. The client will automatically read configuration from environment variables prefixed with AKAMAI_*. ```javascript const eg = new EdgeGrid({}); // No path, reads from env vars ``` ```javascript // or const eg = new EdgeGrid({ section: 'default' }); ``` -------------------------------- ### Configure Akamai API Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Set up your Akamai API credentials in the `~/.edgerc` file. Ensure the file has restricted permissions (600) for security. ```ini [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij host = akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net ``` ```bash chmod 600 ~/.edgerc ``` -------------------------------- ### Configure EdgeGrid with Local .edgerc File Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Use this method for local development by referencing a local .edgerc file. Ensure the file exists and contains the correct credentials. ```javascript const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); ``` ```bash # Create or edit ~/.edgerc [default] client_token = akab-... client_secret = ...= access_token = akab-... host = akab-...luna.akamaiapis.net ``` -------------------------------- ### Initialize EdgeGrid with Custom Section Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Instantiate the EdgeGrid client by specifying a custom section name. The client will then read configuration from environment variables prefixed with AKAMAI_*. ```javascript const eg = new EdgeGrid({ section: 'production' }); ``` -------------------------------- ### Sign Request with auth() Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Prepare and sign a request configuration object using the auth() method. ```javascript auth(requestOptions: { path: string, method?: string, headers?: object, body?: object | string, qs?: object, headersToSign?: object, responseType?: string, proxy?: object }): EdgeGrid ``` -------------------------------- ### auth() Method Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Prepares and signs an outgoing request using the provided request configuration. It handles the necessary authentication headers. ```APIDOC ## auth() ### Description Prepares and signs an outgoing request using the provided request configuration. It handles the necessary authentication headers. ### Method Signature ```javascript auth(requestOptions: { path: string, method?: string, headers?: object, body?: object | string, qs?: object, headersToSign?: object, responseType?: string, proxy?: object }): EdgeGrid ``` ``` -------------------------------- ### Enable Logging with Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/README.md Enable logging and set the log level to 'debug' and pretty printing to 'true' using environment variables before initializing the EdgeGrid client. Ensure environment variables are set prior to enabling logging. ```javascript const edgeGrid = require('akamai-edgegrid'); // Set environment variables before enabling logging process.env.AKAMAI_LOG_LEVEL = 'debug'; process.env.AKAMAI_LOG_PRETTY = 'true'; var eg = new EdgeGrid({ path: '/path/to/.edgerc', section: '' }); eg.enableLogging(true); ``` -------------------------------- ### Resolve User Home Directory in File Paths Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/helpers.md Expands the tilde (~) character at the beginning of a file path to the user's home directory. This is useful for handling configuration files specified with relative paths. ```javascript helpers.resolveHome('~/.edgerc'); // => "/home/user/.edgerc" (on Unix/Linux/macOS) ``` -------------------------------- ### Environment Variables for Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Lists the environment variables that can be used to configure Akamai API access, including optional logging settings. ```bash AKAMAI_HOST=... AKAMAI_CLIENT_TOKEN=... AKAMAI_CLIENT_SECRET=... AKAMAI_ACCESS_TOKEN=... AKAMAI_LOG_LEVEL=debug # Optional AKAMAI_LOG_PRETTY=true # Optional ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/errors.md Set environment variables to enable debug logging and pretty-print the output for better readability. Initialize the EdgeGrid client and explicitly enable logging. ```javascript process.env.AKAMAI_LOG_LEVEL = 'debug'; process.env.AKAMAI_LOG_PRETTY = 'true'; const eg = new EdgeGrid({ path: '~/.edgerc' }); eg.enableLogging(true); ``` -------------------------------- ### Execute Request with send() Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Execute the prepared request and handle the response or error via a callback function. ```javascript send(callback: (error: Error | null, response?: object, body?: string) => void): EdgeGrid ``` -------------------------------- ### Basic EdgeGrid Request with Type Checking Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/types.md Demonstrates initializing EdgeGrid and making a basic authenticated request. Includes error handling and response status logging. ```typescript import EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); eg.auth({ path: '/api/endpoint', method: 'GET' }).send((error: Error | null, response?, body?) => { if (error) { console.error(error); } else { console.log(response?.status); } }); ``` -------------------------------- ### Handle Configuration Loading Errors Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/edgerc.md Demonstrates how to catch and handle errors during EdgeGrid configuration loading, such as invalid section names or missing credentials. ```javascript try { const config = edgerc('~/.edgerc', 'nonexistent'); } catch (error) { if (error.message.includes('invalid section name')) { console.error('Section not found in .edgerc'); } else if (error.message.includes('Missing')) { console.error('Incomplete credentials:', error.message); } } ``` -------------------------------- ### EdgeGrid Constructor (with explicit credentials) Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Initializes an EdgeGrid client using explicit credential strings for client token, client secret, access token, and host. ```APIDOC ## EdgeGrid(clientToken, clientSecret, accessToken, host, max_body) ### Description Initializes an EdgeGrid client using explicit credential strings. ### Parameters #### Path Parameters - **clientToken** (string) - Required - Client token value from Akamai credentials. Format: `akab-c113ntt0k3n...` - **clientSecret** (string) - Required - Client secret value from Akamai credentials. Format: `C113nt53KR3TN6N90...` - **accessToken** (string) - Required - Access token value from Akamai credentials. Format: `akab-acc35t0k3n...` - **host** (string) - Required - API host hostname, e.g., `akab-h05tnam3...luna.akamaiapis.net`. Protocol prefix `https://` is added if omitted. - **max_body** (number) - Optional - Deprecated parameter. Maximum bytes to include in request signature. Defaults to 131072. ### Throws `Error` if any required parameter is missing or empty. ### Request Example ```javascript const EdgeGrid = require('akamai-edgegrid'); const eg = new EdgeGrid( 'akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj', 'C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=', 'akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij', 'akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net' ); ``` ``` -------------------------------- ### Chain Auth and Send Request Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Demonstrates chaining the `auth` method with the `send` method to sign a request and then immediately send it, handling the response or error in a callback. ```javascript eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET' }).send((err, response, body) => { if (err) { console.error(err); } else { console.log(body); } }); ``` -------------------------------- ### resolveHome Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/helpers.md Expands the tilde (~) character in file paths to the user's home directory. ```APIDOC ## resolveHome(filePath) ### Description Expands `~` in file paths to the user's home directory. ### Parameters #### Path Parameters - **filePath** (string) - Required - File path, potentially starting with `~`. ### Returns `string` — Absolute path with `~` replaced by home directory. ### Example ```javascript helpers.resolveHome('~/.edgerc'); // => "/home/user/.edgerc" (on Unix/Linux/macOS) ``` ``` -------------------------------- ### Configure EdgeGrid with hardcoded credentials Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/README.md Instantiate the EdgeGrid client by directly providing your client token, client secret, access token, and base URI. ```javascript var clientToken = "akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj", clientSecret = "C113nt53KR3TN6N90yVuAgIRwsObLi0E67/N8eRN=", accessToken = "akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij", baseUri = "akab-h05tnam3wl42son7nktnlnnx-kbob3i3v.luna.akamaiapis.net"; var eg = new EdgeGrid(clientToken, clientSecret, accessToken, baseUri); ``` -------------------------------- ### enableLogging() Method Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Enables or configures logging for the client. Accepts a boolean to toggle basic logging or an object for custom logger configuration. ```APIDOC ## enableLogging() ### Description Enables or configures logging for the client. Accepts a boolean to toggle basic logging or an object for custom logger configuration. ### Method Signature ```javascript enableLogging(option: boolean | object): EdgeGrid ``` ``` -------------------------------- ### auth(requestOptions) Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Prepares and signs an HTTP request using EdgeGrid authentication. It takes a request options object and returns the EdgeGrid instance for chaining. ```APIDOC ## auth(requestOptions) ### Description Prepares and signs an HTTP request using EdgeGrid authentication. ### Method Signature ```javascript auth(requestOptions: object): EdgeGrid ``` ### Parameters #### requestOptions (object) - Required Request configuration object. See **Request Options Object** below. ### Request Options Object | Property | Type | Required | Default | Description | |---|---|---|---|---| | path | string | Yes | — | API endpoint path, e.g., `/identity-management/v3/user-profile`. | | method | string | No | 'GET' | HTTP method: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`. | | headers | object | No | {} | Custom HTTP headers. `Content-Type` and `Accept` default to `application/json` if not provided. | | body | object | string | No | undefined | Request body. Objects are automatically JSON-stringified. Strings are sent as-is. | | qs | object | No | undefined | Query string parameters as key-value pairs. | | headersToSign | object | No | {} | Subset of headers to include in the signature (some APIs require specific headers signed). | | responseType | string | No | 'json' | Response format: `'json'`, `'arraybuffer'`, `'text'`. Set to `'arraybuffer'` for binary responses (PDFs, tarballs). | | proxy | object | No | undefined | Proxy configuration with `host`, `port`, `protocol`, and optional `auth` object. | ### Returns `EdgeGrid` — Returns `this` for method chaining. ### Example ```javascript eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET', headers: { 'Accept': 'application/json' }, body: {} }); ``` ### Chaining Example ```javascript eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET' }).send((err, response, body) => { if (err) { console.error(err); } else { console.log(body); } }); ``` ``` -------------------------------- ### EdgeGrid Constructor Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Initializes the EdgeGrid client. Supports both file-based configuration (path and optional section) and direct credential string-based initialization. ```APIDOC ## EdgeGrid Constructor ### Description Initializes the EdgeGrid client. Supports both file-based configuration (path and optional section) and direct credential string-based initialization. ### Method Signatures **File-based:** ```javascript new EdgeGrid({ path: string, section?: string }) ``` **String-based:** ```javascript new EdgeGrid(clientToken: string, clientSecret: string, accessToken: string, host: string) ``` ``` -------------------------------- ### send() Method Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Executes the prepared request and returns the response or an error via a callback function. ```APIDOC ## send() ### Description Executes the prepared request and returns the response or an error via a callback function. ### Method Signature ```javascript send(callback: (error: Error | null, response?: object, body?: string) => void): EdgeGrid ``` ``` -------------------------------- ### Make an authenticated API request Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/README.md Use the `auth` method to configure the request details (path, method, headers, body) and then `send` to execute it. The response body is logged to the console. ```javascript var EdgeGrid = require('akamai-edgegrid'); var eg = new EdgeGrid({ path: '/path/to/.edgerc', section: 'section-header' }); eg.auth({ path: '/identity-management/v3/user-profile', method: 'GET', headers: { 'Accept': "application/json" }, body: {} }); eg.send(function(error, response, body) { console.log(body); }); ``` -------------------------------- ### Initialize EdgeGrid with Specific .edgerc Section Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Load credentials from a specific section within your .edgerc file. Useful when managing multiple Akamai environments (e.g., production, staging). ```javascript // Load production credentials const prodEg = new EdgeGrid({ path: '~/.edgerc', section: 'production' }); // Load staging credentials const stageEg = new EdgeGrid({ path: '~/.edgerc', section: 'staging' }); ``` ```ini [default] client_token = ... client_secret = ... access_token = ... host = ... [production] client_token = ... client_secret = ... access_token = ... host = ... [staging] client_token = ... client_secret = ... access_token = ... host = ... ``` -------------------------------- ### Enable Logging with enableLogging() Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/INDEX.md Enable or configure logging for the EdgeGrid client. ```javascript enableLogging(option: boolean | object): EdgeGrid ``` -------------------------------- ### Enable Logging Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/README.md Shows how to enable logging for the EdgeGrid client. Logging can be enabled globally or by passing a custom logger object. ```javascript eg.enableLogging(true) ``` -------------------------------- ### Download Binary File Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Download a binary file, such as a PDF, and save it to the local filesystem. This requires specifying `responseType: 'arraybuffer'` and using the `fs` module to write the file. ```javascript const fs = require('fs'); eg.auth({ path: '/invoicing-api/v2/contracts/123/invoices/456/files/invoice.pdf', method: 'GET', responseType: 'arraybuffer' }).send((error, response) => { if (error) { console.error(error); return; } fs.writeFile('./invoice.pdf', response.data, 'binary', (err) => { if (err) { console.error('File write failed:', err); } else { console.log('Invoice downloaded successfully'); } }); }); ``` -------------------------------- ### Enable Logging with Custom Logger Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/logger.md Use a custom logger instance by passing an object with `info`, `debug`, `error`, and `warn` methods to `enableLogging`. This allows for integration with existing logging frameworks. ```javascript const customLogger = { info: (obj, msg) => console.log(`[INFO] ${msg}`, obj), debug: (obj, msg) => console.log(`[DEBUG] ${msg}`, obj), error: (obj, msg) => console.error(`[ERROR] ${msg}`, obj), warn: (obj, msg) => console.warn(`[WARN] ${msg}`, obj) }; enableLogging(customLogger); ``` -------------------------------- ### Check .edgerc file Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/quickstart.md Use this command to inspect the contents of your .edgerc file to verify credentials. ```bash cat ~/.edgerc ``` -------------------------------- ### Provide Explicit Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Pass individual credential strings directly to the constructor for explicit configuration. This method is useful when .edgerc files are not used. ```javascript const eg = new EdgeGrid( clientToken, // 'akab-c113ntt0k3n...' clientSecret, // 'C113nt53KR3TN6N90...' accessToken, // 'akab-acc35t0k3n...' host, // 'akab-h05tnam3...luna.akamaiapis.net' or 'https://akab-...' max_body // Optional (deprecated): 131072 ); ``` -------------------------------- ### Enable EdgeGrid Logging via Environment Variables Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/api-reference/EdgeGrid.md Configure EdgeGrid logging by setting environment variables `AKAMAI_LOG_LEVEL` and `AKAMAI_LOG_PRETTY`, then calling `enableLogging(true)`. This enables debug and diagnostic output. ```javascript process.env.AKAMAI_LOG_LEVEL = 'debug'; process.env.AKAMAI_LOG_PRETTY = 'true'; const eg = new EdgeGrid({ path: '~/.edgerc', section: 'default' }); eg.enableLogging(true); ``` -------------------------------- ### Configure EdgeGrid with Environment Variables for Docker/Kubernetes Source: https://github.com/akamai/akamaiopen-edgegrid-node/blob/master/_autodocs/configuration.md Configure the EdgeGrid client using environment variables, suitable for Docker or Kubernetes deployments. The client automatically loads credentials from AKAMAI_* prefixed environment variables. ```javascript const eg = new EdgeGrid({}); // Loads from AKAMAI_* env vars ``` ```yaml apiVersion: v1 kind: Secret metadata: name: akamai-credentials type: Opaque stringData: AKAMAI_HOST: "akab-...luna.akamaiapis.net" AKAMAI_CLIENT_TOKEN: "akab-..." AKAMAI_CLIENT_SECRET: "..." AKAMAI_ACCESS_TOKEN: "akab-..." --- apiVersion: v1 kind: Pod spec: containers: - name: app envFrom: - secretRef: name: akamai-credentials ```