### Add and Run an Example Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Create a new TypeScript file in the examples directory and make it executable. Then, run the example using pnpm. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ pnpm tsn -T examples/.ts ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Run these commands to install all necessary dependencies and build the project's output files. ```sh $ pnpm install $ pnpm build ``` -------------------------------- ### Install PostGrid Node.js Library Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Install the library using npm. ```sh npm install postgrid-node ``` -------------------------------- ### Install and Initialize PostGrid Client Source: https://context7.com/postgrid/postgrid-node/llms.txt Install the postgrid-node package and instantiate the PostGrid client. API keys are read from environment variables by default. Configure retry attempts, timeouts, and logging levels. ```bash npm install postgrid-node ``` ```typescript import PostGrid from 'postgrid-node'; // API keys default to process.env['POSTGRID_PRINT_MAIL_API_KEY'] // and process.env['POSTGRID_ADDRESS_VERIFICATION_API_KEY'] const client = new PostGrid({ printMailAPIKey: process.env['POSTGRID_PRINT_MAIL_API_KEY'], addressVerificationAPIKey: process.env['POSTGRID_ADDRESS_VERIFICATION_API_KEY'], maxRetries: 2, // default; retries on network errors, 408, 409, 429, 5xx timeout: 60_000, // default 60 seconds logLevel: 'warn', // 'debug' | 'info' | 'warn' | 'error' | 'off' }); ``` -------------------------------- ### Install from Git Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Use this command to install the Postgrid Node.js package directly from its GitHub repository using SSH. ```sh $ npm install git+ssh://git@github.com:postgrid/postgrid-node.git ``` -------------------------------- ### Create and Send Bulk Mail Campaigns Source: https://context7.com/postgrid/postgrid-node/llms.txt Guides through creating a campaign by linking a mailing list with an order profile, polling for status changes, and initiating the send process. Supports optional future send dates. ```typescript const letterProfile = await client.printMail.orderProfiles.letters.create({ html: '

Dear {{to.firstName}}, you have a special offer!

', from: 'contact_sender123', description: 'Q4 Promo Letter Profile', color: false, size: 'us_letter', mailingClass: 'standard_class', }); ``` ```typescript const campaign = await client.printMail.campaigns.create({ mailingList: 'mailing_list_abc123', letterProfile: letterProfile.id, description: 'Q4 Promo Campaign', metadata: { quarter: 'Q4-2025' }, 'idempotency-key': 'campaign-q4-2025-run1', }); console.log(campaign.id); // 'campaign_...' console.log(campaign.status); // 'drafting' initially ``` ```typescript let c = await client.printMail.campaigns.retrieve(campaign.id); while (c.status === 'drafting') { await new Promise(r => setTimeout(r, 2000)); c = await client.printMail.campaigns.retrieve(campaign.id); } if (c.status === 'changes_required') { console.error('Errors:', c.errors); } else { console.log('Preview URL:', c.orderPreviewURL); // Step 4: Send the campaign const sent = await client.printMail.campaigns.send(campaign.id, { sendDate: '2025-12-01T09:00:00Z', // optional future date }); console.log(sent.status); // 'creating_orders' } ``` ```typescript for await (const camp of client.printMail.campaigns.list()) { console.log(camp.id, camp.status, camp.createdCount); } ``` -------------------------------- ### Configure Node.js Proxy with PostGrid Client Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Configure proxy behavior for Node.js environments by providing custom `fetchOptions` with a `ProxyAgent` instance. This example uses `undici` for proxy configuration. ```typescript import PostGrid from 'postgrid-node'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new PostGrid({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Polyfill Global Fetch Client Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Replace the global `fetch` function with a custom implementation if needed, for example, using a library like `my-fetch`. ```typescript import fetch from 'my-fetch'; globalThis.fetch = fetch; ``` -------------------------------- ### Access Raw Response Data with .asResponse() and .withResponse() Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Use `.asResponse()` to get the raw `Response` object without consuming the body, allowing custom parsing. Use `.withResponse()` to get both the parsed data and the raw `Response` object, which consumes the body. ```typescript const client = new PostGrid(); const response = await client.addressVerification.verify({ address: 'address' }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object const { data: response, response: raw } = await client.addressVerification .verify({ address: 'address' }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(response.data); ``` -------------------------------- ### Get Parsed Data and Raw Response Together Source: https://context7.com/postgrid/postgrid-node/llms.txt Utilize `.withResponse()` to retrieve both the parsed data from the API response and the raw `Response` object simultaneously. This is beneficial when you need both the processed information and response metadata like headers. ```typescript const { data, response } = await client.printMail.letters .create({ to: 'contact_abc123', from: 'contact_xyz789', html: 'Hello', }) .withResponse(); console.log(response.headers.get('x-request-id')); console.log(data.id); // letter id ``` -------------------------------- ### Configure Deno Proxy with PostGrid Client Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Configure proxy settings for Deno runtime by creating a `Deno.HttpClient` with proxy details and passing it as `client` within `fetchOptions`. ```typescript import PostGrid from 'npm:postgrid-node'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new PostGrid({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Configure Bun Proxy with PostGrid Client Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Configure proxy settings for Bun runtime by passing a `proxy` string within `fetchOptions` when instantiating the PostGrid client. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Instantiate PostGrid Client with Fetch Options Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Provide a `fetchOptions` object when instantiating the client to set custom fetch options. Request-specific options override client options. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ fetchOptions: { // `RequestInit` options }, }); ``` -------------------------------- ### Letters API Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Create and manage letters for sending via PostGrid. This includes creating, retrieving, listing, deleting, and getting URLs for letters. ```APIDOC ## POST /print-mail/v1/letters ### Description Creates a new letter. ### Method POST ### Endpoint /print-mail/v1/letters ### Request Body - **params** (object) - Required - Parameters for creating a letter. ### Response #### Success Response (200) - **Letter** (object) - Details of the created letter. ``` ```APIDOC ## GET /print-mail/v1/letters/{id} ### Description Retrieves a specific letter by its ID. ### Method GET ### Endpoint /print-mail/v1/letters/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the letter. ### Response #### Success Response (200) - **Letter** (object) - Details of the retrieved letter. ``` ```APIDOC ## GET /print-mail/v1/letters ### Description Retrieves a list of letters. ### Method GET ### Endpoint /print-mail/v1/letters ### Request Body - **params** (object) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **LettersSkipLimit** (object) - A list of letters with pagination information. ``` ```APIDOC ## DELETE /print-mail/v1/letters/{id} ### Description Deletes a specific letter by its ID. ### Method DELETE ### Endpoint /print-mail/v1/letters/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the letter to delete. ### Response #### Success Response (200) - **Letter** (object) - Response indicating the result of the delete operation. ``` ```APIDOC ## GET /print-mail/v1/letters/{id}/url ### Description Retrieves the URL for a specific letter. ### Method GET ### Endpoint /print-mail/v1/letters/{id}/url ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the letter. ### Response #### Success Response (200) - **LetterRetrieveURLResponse** (object) - The URL to access the letter. ``` -------------------------------- ### Add Undocumented Request Parameters Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Use `// @ts-expect-error` to add undocumented parameters. For GET requests, extra parameters go in the query; for others, they go in the body. ```typescript client.printMail.contacts.create({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Run Tests Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Execute all tests in the repository using the pnpm test command. ```sh $ pnpm run test ``` -------------------------------- ### Link Local Repository with pnpm Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Clone the repository, link it globally, and then link it to your local package using pnpm. ```sh # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link --global postgrid-node ``` -------------------------------- ### Pass Custom Fetch Client to PostGrid Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Initialize the PostGrid client with a custom `fetch` function by passing it in the options object. ```typescript import PostGrid from 'postgrid-node'; import fetch from 'my-fetch'; const client = new PostGrid({ fetch }); ``` -------------------------------- ### Create a Contact with PostGrid API Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Instantiate the PostGrid client and create a new contact. Ensure the POSTGRID_PRINT_MAIL_API_KEY environment variable is set. ```js import PostGrid from 'postgrid-node'; const client = new PostGrid({ printMailAPIKey: process.env['POSTGRID_PRINT_MAIL_API_KEY'], // This is the default and can be omitted }); const contact = await client.printMail.contacts.create({ addressLine1: 'addressLine1', countryCode: 'countryCode', firstName: 'firstName', }); console.log(contact.id); ``` -------------------------------- ### PostGrid Node.js Client Initialization and Error Handling Source: https://context7.com/postgrid/postgrid-node/llms.txt Initialize the PostGrid client with API keys, retry settings, and timeouts. Catch specific API errors and connection timeouts. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ printMailAPIKey: process.env['POSTGRID_PRINT_MAIL_API_KEY'], maxRetries: 3, timeout: 30_000, }); try { const letter = await client.printMail.letters.create({ to: 'contact_invalid', from: 'contact_abc', html: 'Hello', }); } catch (err) { if (err instanceof PostGrid.APIError) { console.error('Status:', err.status); // 400, 401, 403, 404, 422, 429, 500 console.error('Name:', err.name); // 'BadRequestError', 'AuthenticationError', etc. console.error('Headers:', err.headers); } else if (err instanceof PostGrid.APIConnectionTimeoutError) { console.error('Request timed out'); } else { throw err; } } ``` ```typescript // Per-request overrides const result = await client.addressVerification.verify( { address: '145 Mulberry St, New York, NY 10013, US' }, { maxRetries: 0, timeout: 5_000 }, ); ``` -------------------------------- ### Publish Manually Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Run the bin/publish-npm script to manually release a package. Ensure the NPM_TOKEN environment variable is set. ```sh bin/publish-npm ``` -------------------------------- ### Create Template Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Creates a new template. Accepts an object with template details and returns the created template object. ```APIDOC ## POST /print-mail/v1/templates ### Description Creates a new template. ### Method POST ### Endpoint /print-mail/v1/templates ### Request Body - **params** (object) - Required - Object containing template details. ### Response #### Success Response (200) - **template** (Template) - The created template object. ``` -------------------------------- ### Create, Update, and Use Mail Templates Source: https://context7.com/postgrid/postgrid-node/llms.txt Demonstrates creating a reusable HTML template with merge variables, updating it, and then using the template ID when creating a letter order. Templates support `{{variableName}}` syntax for dynamic content. ```typescript const template = await client.printMail.templates.create({ description: 'Welcome Letter Template', html: `

Dear {{to.firstName}} {{to.lastName}},

Welcome to {{companyName}}!

Your account number is {{accountNumber}}.

`, metadata: { category: 'onboarding' }, }); console.log(template.id); // 'template_...' ``` ```typescript const updated = await client.printMail.templates.update(template.id, { html: `

Hello {{to.firstName}},

Welcome aboard at {{companyName}}!

`, description: 'Updated Welcome Letter', }); ``` ```typescript const letter = await client.printMail.letters.create({ to: 'contact_abc123', from: 'contact_xyz789', template: template.id, mergeVariables: { companyName: 'PostGrid', accountNumber: 'ACC-0001' }, }); ``` ```typescript for await (const t of client.printMail.templates.list({ search: 'Welcome' })) { console.log(t.id, t.description); } ``` ```typescript await client.printMail.templates.delete(template.id); ``` -------------------------------- ### Manage Mailing Lists Source: https://context7.com/postgrid/postgrid-node/llms.txt Shows how to create, update, list, and delete mailing lists for bulk mail campaigns. Includes importing contacts via CSV and polling the import job status. ```typescript const mailingList = await client.printMail.mailingLists.create({ description: 'Q4 Promotion List', metadata: { campaign: 'q4-2025', region: 'us-east' }, }); console.log(mailingList.id); // 'mailing_list_...' ``` ```typescript await client.printMail.mailingLists.update(mailingList.id, { description: 'Q4 Promotion List — Updated', }); ``` ```typescript for await (const ml of client.printMail.mailingLists.list()) { console.log(ml.id, ml.description); } ``` ```typescript const importJob = await client.printMail.mailingListImports.create({ mailingList: mailingList.id, fileType: 'csv', // attach file or provide URL depending on your setup }); console.log(importJob.id); // poll until status is complete ``` ```typescript const importStatus = await client.printMail.mailingListImports.retrieve(importJob.id); console.log(importStatus.verificationStatusCount); ``` ```typescript await client.printMail.mailingLists.delete(mailingList.id); ``` -------------------------------- ### Link Local Repository with Yarn Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Clone the repository, link it globally, and then link it to your local package using Yarn. ```sh # Clone $ git clone https://www.github.com/postgrid/postgrid-node $ cd postgrid-node # With yarn $ yarn link $ cd ../my-package $ yarn link postgrid-node ``` -------------------------------- ### Create a Bank Account for Cheques Source: https://context7.com/postgrid/postgrid-node/llms.txt Set up a bank account for sending cheques. US accounts require 'accountNumber' and 'routingNumber'. Canadian accounts require 'accountNumber', 'routeNumber', and 'transitNumber'. A signature is mandatory. ```typescript // First create a bank account const bankAccount = await client.printMail.bankAccounts.create({ accountNumber: '123456789', routingNumber: '021000021', bankCountryCode: 'US', bankName: 'Chase Bank', bankPrimaryLine: '270 Park Ave', bankSecondaryLine: 'New York, NY 10017', signatureText: 'John Smith', }); console.log(bankAccount.id); // 'bank_account_...' ``` -------------------------------- ### Create Self-Mailer Order Profiles Source: https://context7.com/postgrid/postgrid-node/llms.txt Set up self-mailer profiles, specifying inside and outside HTML content, and size. ```typescript const selfMailerProfile = await client.printMail.orderProfiles.selfMailers.create({ from: 'contact_sender123', insideHTML: '

Inside

', outsideHTML: '

Outside

', size: '8.5x11_bifold', }); ``` -------------------------------- ### List Templates Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Retrieves a list of all templates. Supports pagination parameters like skip and limit. ```APIDOC ## GET /print-mail/v1/templates ### Description Retrieves a list of all templates. ### Method GET ### Endpoint /print-mail/v1/templates ### Parameters #### Query Parameters - **params** (object) - Optional - Object containing pagination parameters (e.g., skip, limit). ### Response #### Success Response (200) - **templates** (TemplatesSkipLimit) - An object containing a list of templates and pagination information. ``` -------------------------------- ### Create Cheque Order Profiles Source: https://context7.com/postgrid/postgrid-node/llms.txt Configure cheque profiles with bank account details, currency, memo, and size. ```typescript const chequeProfile = await client.printMail.orderProfiles.cheques.create({ from: 'contact_sender123', bankAccount: 'bank_account_abc123', currencyCode: 'USD', memo: 'Payment', size: 'us_letter', }); ``` -------------------------------- ### Accessing Raw Responses Source: https://context7.com/postgrid/postgrid-node/llms.txt Demonstrates how to access the raw fetch Response object using `.asResponse()` for immediate access to headers, or `.withResponse()` to retrieve both the parsed data and the raw Response. ```APIDOC ## Accessing Raw Responses Use `.asResponse()` to get the raw `fetch` `Response` object (headers available immediately without consuming the body) or `.withResponse()` to get both the parsed data and the raw `Response`. ```ts // .asResponse() — access headers before body is consumed const rawResponse = await client.addressVerification .verify({ address: '145 Mulberry St, New York, NY 10013, US' }) .asResponse(); console.log(rawResponse.headers.get('x-request-id')); console.log(rawResponse.status); // .withResponse() — parsed data + raw Response together const { data, response } = await client.printMail.letters .create({ to: 'contact_abc123', from: 'contact_xyz789', html: 'Hello', }) .withResponse(); console.log(response.headers.get('x-request-id')); console.log(data.id); // letter id ``` ``` -------------------------------- ### Manage Contacts with PostGrid Node.js Client Source: https://context7.com/postgrid/postgrid-node/llms.txt Use this to create, retrieve, list, and delete contacts. Either `firstName` or `companyName` is required for contact creation. Address verification is automatic in live mode, and PostGrid handles deduplication. ```typescript // Create a contact (with firstName) const contact = await client.printMail.contacts.create({ firstName: 'Kevin', lastName: 'Smith', companyName: 'Acme Corp', addressLine1: '145 Mulberry St', addressLine2: 'Suite 300', city: 'New York', provinceOrState: 'NY', postalOrZip: '10013', countryCode: 'US', email: 'kevin@acme.com', metadata: { customerId: 'cust_001' }, }); console.log(contact.id); // 'contact_...' console.log(contact.addressStatus); // 'verified' | 'corrected' | 'failed' console.log(contact.live); // true in live mode ``` ```typescript // Retrieve a contact const fetched = await client.printMail.contacts.retrieve(contact.id); ``` ```typescript // List contacts with auto-pagination const allContacts: typeof contact[] = []; for await (const c of client.printMail.contacts.list({ limit: 50, search: 'New York' })) { allContacts.push(c); } console.log(allContacts.length); ``` ```typescript // Manual pagination let page = await client.printMail.contacts.list({ limit: 20 }); console.log(page.data); // Contact[] console.log(page.totalCount); while (page.hasNextPage()) { page = await page.getNextPage(); } ``` ```typescript // Delete const deleted = await client.printMail.contacts.delete(contact.id); console.log(deleted.deleted); // true ``` -------------------------------- ### Retrieve Self-Mailer Preview URL Source: https://context7.com/postgrid/postgrid-node/llms.txt Obtain a temporary URL to preview a created self-mailer. The URL expires after 15 minutes. ```typescript // Retrieve preview URL const smUrl = await client.printMail.selfMailers.retrieveURL(selfMailer.id); console.log(smUrl.url); // expires after 15 minutes ``` -------------------------------- ### Report Samples API Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Manage samples for reports within the Postgrid Print & Mail service. ```APIDOC ## POST /print-mail/v1/reports/{id}/samples ### Description Creates a sample for a specific report. ### Method POST ### Endpoint /print-mail/v1/reports/{id}/samples ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the report for which to create a sample. ### Request Body - **params** (object) - Required - Parameters for creating the report sample. ### Response #### Success Response (200) - **ReportSample** (object) - Details of the created report sample. ``` -------------------------------- ### Configure Log Level with Client Option Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Set the `logLevel` option during client initialization to control the verbosity of log messages. This overrides the `POSTGRID_LOG` environment variable. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ logLevel: 'debug', // Show all log messages }); ``` -------------------------------- ### Create and Manage Letter Order Profiles Source: https://context7.com/postgrid/postgrid-node/llms.txt Use this to create, update, and delete letter profiles. Ensure 'from' and 'size' are correctly specified. ```typescript const letterProfile = await client.printMail.orderProfiles.letters.create({ html: '

Hello {{to.firstName}}!

', from: 'contact_sender123', size: 'us_letter', color: true, doubleSided: false, mailingClass: 'first_class', }); ``` ```typescript await client.printMail.orderProfiles.letters.update(letterProfile.id, { color: false, description: 'Updated Letter Profile', }); ``` ```typescript await client.printMail.orderProfiles.letters.delete(letterProfile.id); ``` -------------------------------- ### Configure Custom Logger with Pino Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Provide a custom logger instance, such as one from `pino`, to the client constructor. The `logLevel` option still determines which messages are sent to the custom logger. ```typescript import PostGrid from 'postgrid-node'; import pino from 'pino'; const logger = pino(); const client = new PostGrid({ logger: logger.child({ name: 'PostGrid' }), logLevel: 'debug', // Send all messages to pino, allowing it to filter }); ``` -------------------------------- ### Iterate Through All Pages of List Results Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Use the `for await...of` syntax to automatically fetch and iterate through all items across paginated list results from the API. ```ts async function fetchAllLetters(params) { const allLetters = []; // Automatically fetches more pages as needed. for await (const letter of client.printMail.letters.list({ limit: 100 })) { allLetters.push(letter); } return allLetters; } ``` -------------------------------- ### Create and Manage Reports Source: https://context7.com/postgrid/postgrid-node/llms.txt Generate, update, and delete reports for analyzing mailing activity. Use sample and export functionalities as needed. ```typescript // Create a report const report = await client.printMail.reports.create({ description: 'Monthly delivery report', }); console.log(report.id); // 'report_...' ``` ```typescript // Update a report await client.printMail.reports.update(report.id, { description: 'Updated delivery report', }); ``` ```typescript // Generate a report sample const sample = await client.printMail.reports.sample({ // sample params as required by your report type }); console.log(sample); ``` ```typescript // Create a report sample for a specific report const reportSample = await client.printMail.reports.samples.create(report.id, {}); ``` ```typescript // Export a report const exportJob = await client.printMail.reports.exports.create(report.id, {}); console.log(exportJob.id); ``` ```typescript // Retrieve export status const exportStatus = await client.printMail.reports.exports.retrieve(exportJob.id, { reportID: report.id, }); ``` ```typescript // List reports for await (const r of client.printMail.reports.list()) { console.log(r.id, r.description); } ``` ```typescript // Delete a report await client.printMail.reports.delete(report.id); ``` -------------------------------- ### Create a Self-Mailer Source: https://context7.com/postgrid/postgrid-node/llms.txt Use this to create a folded self-mailer with HTML content. Specify 'to', 'from', 'insideHTML', 'outsideHTML', 'size', 'mailingClass', 'mergeVariables', and 'sendDate'. ```typescript const selfMailer = await client.printMail.selfMailers.create({ to: 'contact_abc123', from: 'contact_xyz789', insideHTML: '

Inside Content

Special offer inside!

', outsideHTML: '

Outside Cover

', size: '8.5x11_bifold', mailingClass: 'first_class', mergeVariables: { offerCode: 'SPRING25' }, sendDate: '2025-06-01', }); console.log(selfMailer.id); console.log(selfMailer.status); // 'ready' | 'printing' | 'completed' ``` -------------------------------- ### Lint and Format Code Source: https://github.com/postgrid/postgrid-node/blob/main/CONTRIBUTING.md Use these commands to lint the code and automatically fix any linting issues. ```sh $ pnpm lint ``` ```sh $ pnpm fix ``` -------------------------------- ### Manually Paginate Through List Results Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Fetch a single page of results and then use convenience methods like `hasNextPage()` and `getNextPage()` to manually paginate through the data. ```ts let page = await client.printMail.letters.list({ limit: 100 }); for (const letter of page.data) { console.log(letter); } // Convenience methods are provided for manually paginating: while (page.hasNextPage()) { page = await page.getNextPage(); // ... } ``` -------------------------------- ### Use TypeScript Definitions for API Requests Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Import and utilize TypeScript definitions for request parameters and response fields when interacting with the address verification API. Ensure the POSTGRID_ADDRESS_VERIFICATION_API_KEY environment variable is set. ```ts import PostGrid from 'postgrid-node'; const client = new PostGrid({ addressVerificationAPIKey: process.env['POSTGRID_ADDRESS_VERIFICATION_API_KEY'], // This is the default and can be omitted }); const params: PostGrid.AddressVerificationVerifyParams = { address: 'address' }; const response: PostGrid.AddressVerificationVerifyResponse = await client.addressVerification.verify(params); ``` -------------------------------- ### Manage Sub-Organizations Source: https://context7.com/postgrid/postgrid-node/llms.txt Retrieve and manage sub-organizations, including listing, retrieving by ID, updating settings, and fetching users. ```typescript // List sub-organizations for await (const org of client.printMail.subOrganizations.list()) { console.log(org.id); } ``` ```typescript // Retrieve a specific sub-organization const org = await client.printMail.subOrganizations.retrieve('sub_org_id'); console.log(org.id); ``` ```typescript // Retrieve users in a sub-organization const users = await client.printMail.subOrganizations.retrieveUsers('sub_org_id'); console.log(users); ``` ```typescript // Update sub-organization settings await client.printMail.subOrganizations.update({ // settings params }); ``` -------------------------------- ### Create Postcard Order Profiles Source: https://context7.com/postgrid/postgrid-node/llms.txt Defines settings for postcard profiles, including front and back HTML content, size, and mailing class. ```typescript const postcardProfile = await client.printMail.orderProfiles.postcards.create({ frontHTML: '

Front Side

', backHTML: '

Back Side

', size: '6x4', from: 'contact_sender123', mailingClass: 'standard_class', }); ``` -------------------------------- ### Create US Bank Account with Signature Text Source: https://context7.com/postgrid/postgrid-node/llms.txt Register a US bank account using its account and routing numbers, along with a signature provided as text. Optional 'description' and 'metadata' can be included. ```typescript // US bank account with signature text const usBankAccount = await client.printMail.bankAccounts.create({ accountNumber: '987654321', routingNumber: '021000021', bankCountryCode: 'US', bankName: 'Bank of America', signatureText: 'Jane Doe', description: 'Primary operating account', metadata: { accountType: 'checking' }, }); ``` -------------------------------- ### Create a Physical Cheque Source: https://context7.com/postgrid/postgrid-node/llms.txt Generate and mail a physical cheque. Amounts are in cents. Supports optional logo, memo, message, and specific mailing details. Currency can be 'USD' or 'CAD'. ```typescript // Create a cheque const cheque = await client.printMail.cheques.create({ to: 'contact_recipient123', from: 'contact_sender456', bankAccount: bankAccount.id, amount: 150000, // $1,500.00 in cents currencyCode: 'USD', number: 1001, memo: 'Invoice #INV-2025-001', message: 'Thank you for your business', size: 'us_letter', // 'us_letter' | 'us_legal' mailingClass: 'first_class', sendDate: '2025-09-15', }); console.log(cheque.id); console.log(cheque.url); // preview PDF URL ``` -------------------------------- ### Order Profiles Source: https://context7.com/postgrid/postgrid-node/llms.txt Manage reusable configurations for letters, postcards, cheques, and self-mailers. This includes creating, updating, and deleting profiles. ```APIDOC ## Order Profiles — `client.printMail.orderProfiles` Order profiles store reusable configurations for letters, postcards, cheques, and self-mailers used in campaigns. Profiles define the content, size, mailing class, and other settings shared across all orders in a campaign. ### Create Letter Profile ```ts await client.printMail.orderProfiles.letters.create({ html: '

Hello {{to.firstName}}!

', from: 'contact_sender123', size: 'us_letter', color: true, doubleSided: false, mailingClass: 'first_class', }); ``` ### Create Postcard Profile ```ts await client.printMail.orderProfiles.postcards.create({ frontHTML: '

Front Side

', backHTML: '

Back Side

', size: '6x4', from: 'contact_sender123', mailingClass: 'standard_class', }); ``` ### Create Cheque Profile ```ts await client.printMail.orderProfiles.cheques.create({ from: 'contact_sender123', bankAccount: 'bank_account_abc123', currencyCode: 'USD', memo: 'Payment', size: 'us_letter', }); ``` ### Create Self-Mailer Profile ```ts await client.printMail.orderProfiles.selfMailers.create({ from: 'contact_sender123', insideHTML: '

Inside

', outsideHTML: '

Outside

', size: '8.5x11_bifold', }); ``` ### Update Letter Profile ```ts await client.printMail.orderProfiles.letters.update(letterProfile.id, { color: false, description: 'Updated Letter Profile', }); ``` ### Delete Letter Profile ```ts await client.printMail.orderProfiles.letters.delete(letterProfile.id); ``` ``` -------------------------------- ### Create Postcards with PostGrid Node.js Client Source: https://context7.com/postgrid/postgrid-node/llms.txt Design and send double-sided physical postcards using HTML for front and back, template IDs, or a 2-page PDF. Sender (`from`) is optional. Supports various sizes like `6x4`, `9x6`, and `11x6`. ```typescript // HTML postcard const postcard = await client.printMail.postcards.create({ to: 'contact_abc123', from: 'contact_xyz789', frontHTML: `

Hello {{to.firstName}}!

Visit us at postgrid.com

`, backHTML: `

Return address block here

`, size: '6x4', mailingClass: 'first_class', mergeVariables: { promoCode: 'SAVE20' }, metadata: { batchId: 'batch_001' }, }); console.log(postcard.id); console.log(postcard.url); // signed preview PDF ``` ```typescript // PDF-based postcard const pdfPostcard = await client.printMail.postcards.create({ to: 'contact_abc123', pdf: 'https://example.com/postcard-design.pdf', // 2-page PDF size: '9x6', }); ``` ```typescript // Retrieve preview URL const pcUrl = await client.printMail.postcards.retrieveURL(postcard.id); console.log(pcUrl.url); ``` ```typescript // List with auto-pagination for await (const pc of client.printMail.postcards.list()) { console.log(pc.id, pc.status); } ``` -------------------------------- ### Configure Default Retries for PostGrid Requests Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Configure the default number of retries for all requests by setting the maxRetries option during client initialization. Set to 0 to disable retries. ```js // Configure the default for all requests: const client = new PostGrid({ maxRetries: 0, // default is 2 }); ``` -------------------------------- ### Create Letters with PostGrid Node.js Client Source: https://context7.com/postgrid/postgrid-node/llms.txt Generate physical letters using HTML content, saved template IDs, or PDFs. Supports color, double-sided printing, address placement, attached PDFs, merge variables, and scheduled send dates. Requires `printMailAPIKey` for initialization. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ printMailAPIKey: process.env['POSTGRID_PRINT_MAIL_API_KEY'] }); // Create a letter with inline HTML and inline contact creation const letter = await client.printMail.letters.create({ to: { firstName: 'Jane', lastName: 'Doe', addressLine1: '20 Bay St', city: 'Toronto', provinceOrState: 'ON', postalOrZip: 'M5J 2N8', countryCode: 'CA', }, from: 'contact_abc123', // or inline contact object html: `

Dear {{to.firstName}},

Your order {{orderId}} has shipped!

`, mergeVariables: { orderId: 'ORD-9999' }, color: false, doubleSided: false, size: 'us_letter', // 'us_letter' | 'a4' mailingClass: 'first_class', addressPlacement: 'top_first_page', sendDate: '2025-12-01', metadata: { campaignId: 'c_001' }, }); console.log(letter.id); // 'letter_...' console.log(letter.status); // 'ready' | 'printing' | 'completed' | 'cancelled' console.log(letter.url); // signed preview PDF URL ``` ```typescript // Create with a saved template ID const letterFromTemplate = await client.printMail.letters.create({ to: 'contact_xyz789', from: 'contact_abc123', template: 'template_456', mergeVariables: { firstName: 'Alice' }, }); ``` ```typescript // Retrieve preview URL (document management addon required) const urlResp = await client.printMail.letters.retrieveURL(letter.id); console.log(urlResp.url); ``` ```typescript // Cancel a letter const cancelled = await client.printMail.letters.delete(letter.id); console.log(cancelled.status); // 'cancelled' ``` ```typescript // List all letters for await (const l of client.printMail.letters.list({ limit: 100 })) { console.log(l.id, l.imbStatus); // track IMB status } ``` -------------------------------- ### PrintMail - Campaigns - Create Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Creates a new campaign for print mail services. ```APIDOC ## POST /print-mail/v1/campaigns ### Description Creates a new campaign. ### Method POST ### Endpoint /print-mail/v1/campaigns ### Parameters #### Request Body - **...params** (object) - Required - Parameters for creating a campaign. ``` -------------------------------- ### Verify US/Canadian Address (Structured) Source: https://context7.com/postgrid/postgrid-node/llms.txt Verify and standardize a US or Canadian address using a structured object. Use `.catch()` to handle potential `PostGrid.APIError` exceptions, checking `err.status` and `err.name` for details. ```typescript import PostGrid from 'postgrid-node'; const client = new PostGrid({ addressVerificationAPIKey: process.env['POSTGRID_ADDRESS_VERIFICATION_API_KEY'], }); // Structured address const structuredResult = await client.addressVerification.verify({ address: { line1: '145 Mulberry St', city: 'New York', provinceOrState: 'NY', postalOrZip: '10013', country: 'us', }, includeDetails: true, }).catch((err) => { if (err instanceof PostGrid.APIError) { console.error(err.status, err.name); // e.g. 400, 'BadRequestError' } throw err; }); console.log(structuredResult.data.errors); // field-level errors if any ``` -------------------------------- ### PrintMail - Bank Accounts - Create Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Creates a new bank account for print mail services. ```APIDOC ## POST /print-mail/v1/bank_accounts ### Description Creates a new bank account. ### Method POST ### Endpoint /print-mail/v1/bank_accounts ### Parameters #### Request Body - **...params** (object) - Required - Parameters for creating a bank account. ``` -------------------------------- ### Verify International Address (Freeform) Source: https://context7.com/postgrid/postgrid-node/llms.txt Verify and standardize international addresses from any country using a freeform string. Include `geoData=true` for latitude/longitude and accuracy, and `includeDetails=true` for premise and thoroughfare breakdowns. The response includes a `summary` with match scores. ```typescript // Freeform international const intlFreeform = await client.intlAddressVerification.verify({ address: '10 Downing Street, London, SW1A 2AA, GB', includeDetails: true, geoData: true, properCase: true, }); console.log(intlFreeform.data.status); // 'verified' console.log(intlFreeform.data.formattedAddress); // formatted string console.log(intlFreeform.data.geoData?.latitude); console.log(intlFreeform.data.summary?.matchScore); ``` -------------------------------- ### Create Canadian Bank Account with Signature Image Source: https://context7.com/postgrid/postgrid-node/llms.txt Register a Canadian bank account using account, route, and transit numbers, with a signature provided as a URL to an image. Specify the 'bankCountryCode' as 'CA'. ```typescript // Canadian bank account with signature image URL const caBankAccount = await client.printMail.bankAccounts.create({ accountNumber: '1234567', routeNumber: '001', transitNumber: '00012', bankCountryCode: 'CA', bankName: 'RBC Royal Bank', signatureImage: 'https://example.com/signature.png', }); ``` -------------------------------- ### Configure Default Timeout for PostGrid Requests Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Set the default request timeout for all API calls by providing the timeout option in milliseconds during client initialization. ```ts // Configure the default for all requests: const client = new PostGrid({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); ``` -------------------------------- ### Retrieve Template Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Retrieves a specific template by its ID. Returns the template object if found. ```APIDOC ## GET /print-mail/v1/templates/{id} ### Description Retrieves a specific template by its ID. ### Method GET ### Endpoint /print-mail/v1/templates/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the template to retrieve. ### Response #### Success Response (200) - **template** (Template) - The requested template object. ``` -------------------------------- ### Address Verification - Verify Source: https://github.com/postgrid/postgrid-node/blob/main/api.md Verifies a given address using the Address Verification API. ```APIDOC ## POST /v1/addver/verifications ### Description Verifies a given address. ### Method POST ### Endpoint /v1/addver/verifications ### Parameters #### Request Body - **...params** (object) - Required - Parameters for address verification. ``` -------------------------------- ### Verify International Address (Structured) Source: https://context7.com/postgrid/postgrid-node/llms.txt Verify and standardize international addresses using a structured object. `includeDetails=true` provides premise and thoroughfare breakdowns, while `geoData=true` adds latitude, longitude, and accuracy. Check `data.errors` for field-level issues. ```typescript // Structured international const intlStructured = await client.intlAddressVerification.verify({ address: { line1: '10 Downing Street', city: 'London', provinceOrState: 'England', postalOrZip: 'SW1A 2AA', country: 'GB', }, includeDetails: true, }); console.log(intlStructured.data.details?.building); console.log(intlStructured.data.details?.street); console.log(intlStructured.data.errors); ``` -------------------------------- ### List All Cheques Source: https://context7.com/postgrid/postgrid-node/llms.txt Iterate through all created cheques to retrieve their details, including ID, amount, and status. ```typescript // List all cheques for await (const c of client.printMail.cheques.list()) { console.log(c.id, c.amount, c.status); } ``` -------------------------------- ### Access Raw Response Headers and Status Source: https://context7.com/postgrid/postgrid-node/llms.txt Use `.asResponse()` to access the raw `fetch` `Response` object, allowing immediate access to headers and status before consuming the response body. This is useful for inspecting request metadata. ```typescript const rawResponse = await client.addressVerification .verify({ address: '145 Mulberry St, New York, NY 10013, US' }) .asResponse(); console.log(rawResponse.headers.get('x-request-id')); console.log(rawResponse.status); ``` -------------------------------- ### Configure Per-Request Timeout for PostGrid Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Override the default timeout for a specific request by passing the timeout option in milliseconds as the second argument. ```ts // Override per-request: await client.addressVerification.verify({ address: 'address' }, { timeout: 5 * 1000, }); ``` -------------------------------- ### Handle API Errors with PostGrid Library Source: https://github.com/postgrid/postgrid-node/blob/main/README.md Catch and handle API errors by checking if the error is an instance of PostGrid.APIError. Access properties like status, name, and headers for detailed error information. ```ts const response = await client.addressVerification .verify({ address: 'address' }) .catch(async (err) => { if (err instanceof PostGrid.APIError) { console.log(err.status); // 400 console.log(err.name); // BadRequestError console.log(err.headers); // {server: 'nginx', ...} } else { throw err; } }); ``` -------------------------------- ### Retrieve and List Bank Accounts Source: https://context7.com/postgrid/postgrid-node/llms.txt Fetch a specific bank account by its ID or list all registered bank accounts. Supports iteration over the list of accounts. ```typescript // Retrieve, list, delete const ba = await client.printMail.bankAccounts.retrieve(usBankAccount.id); for await (const account of client.printMail.bankAccounts.list()) { console.log(account.id, account.bankName); } ```