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!