plaid-node

repository·master·Indexed 20 days ago

https://github.com/plaid/plaid-node

The official Node.js client library for the Plaid API, providing typed access to Plaid's financial data services. Version 45.0.0 features a Configuration-based initialization for the PlaidApi client, support for sandbox and production environments, and Promise-based error handling. It includes methods for exchanging public tokens for access tokens, retrieving transactions via transactionsSync or transactionsGet, and downloading Asset Report PDFs.

Tokens
2.9K
Snippets
14
Records
18
Agent score
20%

What's inside plaid-node

  1. Configure the Plaid client

    master

    To use the Plaid API, you must create a Configuration object containing your client_id and secret in the baseOptions.headers. You must also specify a basePath using PlaidEnvironments to determine which environment (e.g., sandbox or production) you are accessing. The baseOptions field accepts standard Axios request options.

    import { Configuration, PlaidApi, PlaidEnvironments } from 'plaid';
    
    const configuration = new Configuration({
      basePath: PlaidEnvironments.sandbox,
      baseOptions: {
        headers: {
          'PLAID-CLIENT-ID': CLIENT_ID,
          'PLAID-SECRET': SECRET,
        },
      },
    });
    
    const plaidClient = new PlaidApi(configuration);
  2. Migrate from pre-9.0.0 to latest

    master

    Version 9.0.0 introduced a major interface change. The library transitioned to using an OpenAPI 3.0.0 specification generated via typescript-axios. Key changes include:

    1. Client Initialization: The plaid.Client constructor is replaced by a Configuration object passed to a PlaidApi instance.
    2. Endpoints: Requests now require a request model object instead of positional arguments. Function names have changed to follow a resourceVerb pattern (e.g., getTransactions becomes transactionsGet). Callbacks are no longer supported; use Promises/async-await.
    3. Error Handling: Errors are now handled via Promise rejection. Error details are located in error.response.data.
    4. Enums: You can use either raw strings or the provided Node enums.
  3. Handle errors in Plaid API calls

    master

    All API methods return promises, allowing you to use try/catch with async/await or .catch() for promise chaining.

    Security Warning: The full error object includes the API configuration object, which contains your PLAID-CLIENT-ID and PLAID-SECRET in the headers. To avoid leaking credentials in logs, do not log the full error object. Instead, log only error.response.data or specific fields from the error response.

    try {
      await plaidClient.transactionsSync(request);
    } catch (error) {
      // Log only the response data to avoid leaking secrets in error.config.headers
      const err = error.response.data;
      console.error(err);
    }
  4. Migrate from version 9.0.0 or later to latest

    master
    Migrating from version 9.0.0 or later to a recent version typically involves minor integration changes. Most users will not need to make any changes. To identify specific breaking changes, consult the client library changelog and look for entries annotated with "Breaking changes in this version" at the top of each major version header.
  5. Troubleshoot empty webhook bodies in Next.js

    master

    If you receive webhooks with empty bodies in Next.js, it is likely due to the bodyParser middleware. To fix this, disable the default body parser in your route config and use the micro buffer to read the raw request body.

    import { buffer } from 'micro'
    
    export default async function handler(req, res) {
      const rawBody = await buffer(req)
      const body = JSON.parse(rawBody.toString())
    
      // Process webhook...
      res.status(200).json({ status: 'ok' })
    }
    
    export const config = {
      api: { bodyParser: false }
    }
  6. Download an Asset Report PDF

    master

    To download an Asset Report as a PDF, use assetReportPdfGet. You must pass responseType: 'arraybuffer' in the second argument (the Axios request options) to receive the binary data.

    import fs from 'fs';
    
    const pdfResp = await plaidClient.assetReportPdfGet(
      {
        asset_report_token: assetReportToken,
      },
      {
        responseType: 'arraybuffer',
      },
    );
    
    fs.writeFileSync('asset_report.pdf', pdfResp.data);
  7. Retrieve transactions using transactionsSync

    master

    The transactionsSync method is the recommended way to retrieve transaction data for a user.

    const response = await plaidClient.transactionsSync({
      access_token
    });
    const transactions = response.data.transactions;
  8. Exchange a public_token for an access_token

    master

    Use itemPublicTokenExchange to exchange a public_token received from Plaid Link for a permanent access_token, which is then used for subsequent API calls like accountsGet.

    const response = await plaidClient.itemPublicTokenExchange({ public_token });
    const access_token = response.data.access_token;
    const accounts_response = await plaidClient.accountsGet({ access_token });
    const accounts = accounts_response.data.accounts;
  9. Retrieve transactions using the legacy transactionsGet method

    master

    You can retrieve transactions for a specific date range using the older transactionsGet method by providing start_date and end_date in 'YYYY-MM-DD' format.

    const today = new Date().toISOString().slice(0, 10);
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)
      .toISOString()
      .slice(0, 10);
    
    const response = await plaidClient.transactionsGet({
      access_token,
      start_date: thirtyDaysAgo,
      end_date: today,
    });
    const transactions = response.data.transactions;
  10. Handle errors in modern Plaid API calls

    master

    Since callbacks are no longer supported, use try/catch blocks or .catch() to handle errors. Error details (like error_code) are found in the response.data property of the caught error.

    try {
      await plaidClient.transactionsGet(request);
    } catch (error) {
      const err = error.response.data;
      // Handle error using err.error_code, etc.
    }