xero-node `refreshTokens` returns `401`

My app has an integration with Xero using the xero-node SDK. I can complete the Xero authentication process using the OAuth workflow without issues and the token set returned by Xero is stored in my database. However, once the access_token has expired (after 30 minutes) and the tokens need to be refreshed, invoking the xeroClient.refreshToken function is failing with the xero API request returning 401.

This is an excerpt of the code from my API route that handles fetching the existing Xero token set, checking if it’s expired and if it’s expired, invoke a helper function that refreshes the token:

const xero = createXeroClient();

    /** check for existing tokenSet in db (xero will return existing tokenSet if org is already connected) */
    let existingTokenSet = await getXeroTokenSet(userId, clientUser.client_id);
    console.log("existing tokens returned");
    /** if tokenSet already exists, check if its expired */
    if (existingTokenSet) {
      console.log("if statement exec");
      /** Token needs to be set in the xero client, even if it's expired - required for xero.refreshToken func */
      await xero.setTokenSet(existingTokenSet);
      await xero.initialize();

      xero.updateTenants(false);
      console.log("update tenants called");

      console.log("token from database", existingTokenSet.refresh_token);
      console.log(
        "check db token expired",
        isXeroTokenExpired(
          existingTokenSet.created_at,
          existingTokenSet.expires_in
        )
      );

      const expired = isXeroTokenExpired(
        existingTokenSet.created_at,
        existingTokenSet.expires_in
      );

      if (expired) {
        console.log("read tokens expired");

        existingTokenSet = await handleXeroTokenRefresh({
          xeroClient: xero,
          refreshToken: existingTokenSet.refresh_token,
          userId,
          clientId: clientUser.client_id,
        });


        console.log("refreshed token returned");

        await xero.setTokenSet(existingTokenSet);
        await xero.updateTenants(false);
      }

This is the helper function that refreshes the tokens, and updates the token set stored in the database:

export const handleXeroTokenRefresh = async ({
refreshToken,
userId,
clientId,
xeroClient,
}: {
refreshToken: string;
userId: string;
clientId: number;
xeroClient: XeroClient;
}) => {
try {
  const refreshTokenSet = await xeroClient.refreshToken().catch((error) => {
    console.error("Error refreshing xero token");
    throw error;
  });

  console.log("Token set received:", refreshTokenSet);

  const validationResult = createXeroTokenSchema.safeParse({
    ...refreshTokenSet,
    expires_in: refreshTokenSet.expires_in,
    user_id: userId,
    client_id: clientId,
  });

  if (!validationResult.success) {
    console.error("Validation error:", validationResult.error);
    throw new Error("Error validating xero token set");
  }

  await deleteXeroToken({ userId, refreshToken, clientId });

  const newTokenSet = await createXeroTokenEntry(validationResult.data);
  console.log("Refreshed token set successfully");
  return newTokenSet;
} catch (error) {
  console.error("Error refreshing xero tokens: ", error);
  throw error;
}
};

This is the error returned by xeroClient.refreshToken():

outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'GET /connections HTTP/1.1rn' +
        'Accept: application/json, text/plain, */*rn' +
        'Authorization: Bearer <redacted>' +
        'User-Agent: axios/1.7.2rn' +
        'Accept-Encoding: gzip, compress, deflate, brrn' +
        'sentry-trace: 0347fa069ac24d93b8917fe33e4ded1c-b81bcb29bbbe68f2-0rn' +
        'baggage: sentry-environment=production,sentry-release=8c0a8d397c87185f2e8f481e427b30f86ff58992,sentry-public_key=7eb42c47637793b35e511de17cd63f43,sentry-trace_id=0347fa069ac24d93b8917fe33e4ded1crn' +
        'x-vercel-id: <redacted>' +
        'Host: api.xero.comrn' +
        'Connection: closern' +
        'rn',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'GET',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/connections',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.xero.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kHighWaterMark)]: 16384,
      [Symbol(kRejectNonStandardBodyWrites)]: false,
      [Symbol(kUniqueHeaders)]: null
    },
    data: {
      Type: null,
      Title: 'Unauthorized',
      Status: 401,
      Detail: 'TokenExpired: token expired at 07/23/2024 04:34:24',
      Instance: '7c4e4c62-e326-4e35-9f33-40c387542c5a',
      Extensions: {}
    }
  }
}

Any help is appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật