next.js implementation
import { NextApiRequest, NextApiResponse } from ‘next’;
const accessToken: string = process.env.HUBSPOT_AUTHORIZATION_TOKEN ?? ‘’;
const fetchContactsFromList = async (listId: number): Promise<string[]> => {
let contactList: string[] = [];
let endpoint = `https://api.hubapi.com/crm/v3/lists/${listId}/memberships\`;
while (endpoint) {
const response = await fetch(endpoint, {
method: ‘GET’,
headers: {
Authorization: `Bearer ${accessToken}`,
‘Content-Type’: ‘application/json’,
},
});
if (!response.ok) {
throw new Error(
`Failed to fetch contacts from list: ${response.statusText}`,
);
}
const data = await response.json();
const contacts = data.results.map((contact: any) => contact.recordId);
contactList = contactList.concat(contacts);
endpoint = data.paging?.next?.link || ‘’;
}
return contactList;
};
const fetchContactDetails = async (contactIds: string[]): Promise<any[]> => {
const chunks = chunkArray(contactIds, 100);
let detailedContacts: any[] = [];
for (const chunk of chunks) {
const response = await fetch(
‘https://api.hubapi.com/crm/v3/objects/contacts/batch/read’,
{
method: ‘POST’,
headers: {
Authorization: `Bearer ${accessToken}`,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
inputs: chunk.map((id) => ({ id })),
}),
},
);
if (!response.ok) {
throw new Error(
`Failed to fetch contact details: ${response.statusText}`,
);
}
const data = await response.json();
detailedContacts = detailedContacts.concat(data.results);
}
return detailedContacts;
};
const chunkArray = (array: any[], size: number) => {
return Array.from({ length: Math.ceil(array.length / size) }, (v, i) =>
array.slice(i * size, i * size + size),
);
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<any | { error: string }>,
): Promise<void> {
const listId: number = 9;
try {
const contactIds = await fetchContactsFromList(listId);
const detailedContacts = await fetchContactDetails(contactIds);
const emailList = detailedContacts.map((contact) => {
const { email, firstname, lastname } = contact.properties;
const displayName =
firstname && lastname ? `${firstname} ${lastname}` : email;
return {
emailAddress: email,
displayableName: displayName,
};
});
res.status(200).json(emailList);
} catch (e: any) {
res.status(500).json({ error: e.message });
}
}
respnse:
[
***{***
***"emailAddress": "bh@hubspot.com",***
***"displayableName": "Brian Halligan"***
***},***
***{***
***"emailAddress": "emailmaria@hubspot.com",***
***"displayableName": "Maria Johnson"***
***}***
]