Youtube Video comments issue with Pagination - Code Node

Hey folks,

I’m trying to fetch YouTube video comments using the YouTube Data API within the n8n Code node, handling pagination to retrieve all comments. The inputs I’m passing are:

• YouTube Video ID

• Google API Key.

The output I am getting is “Comments - No Array”. Can you please help where I am going wrong

Code - // Use URLSearchParams to construct query strings natively

// Define the base URL for the YouTube Data API
const BASE_URL = “https://www.googleapis.com/youtube/v3/commentThreads”;

// Get the first input item
const item = $input.first();

// Extract the videoId and apiKey from the input JSON
const videoId = item.json.VIDEO_ID;
const apiKey = item.json.GOOGLE_API_KEY;

const comments = ;
let nextPageToken = undefined;

do {
// Construct URL parameters
const params = {
part: “snippet”,
videoId: videoId,
key: apiKey,
maxResults: 100 // Maximum number of results per page
};

if (nextPageToken) {
    params.pageToken = nextPageToken;
}

// Build the full URL
const queryString = Object.entries(params).map(([key, value]) => {
    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}).join('&');
const url = `${BASE_URL}?${queryString}`;

// Set up the options for the HTTP request helper
const options = {
    method: "GET",
    uri: url,
    json: true
};

try {
    // Use n8n's built-in HTTP request helper
    const data = await this.helpers.httpRequest(options);

    // Process each comment in the response
    data.items.forEach(item => {
        comments.push(item.snippet.topLevelComment.snippet.textOriginal);
    });

    // Update the nextPageToken
    nextPageToken = data.nextPageToken;

    // Rate limiting: pause between requests to avoid hitting rate limits
    await new Promise(resolve => setTimeout(resolve, 100)); // 100ms delay; adjust as needed
} catch (error) {
    // Handle errors gracefully
    console.error('Error fetching comments:', error.message);
    break;
}

} while (nextPageToken);

// Return the collected comments as an item output for n8n
return [{ json: { comments } }];

Oh, that looks complex. Maybe an easier approach is to use HTTP Request node.

Here’s an example with pagination enabled:

.

:point_right: If my reply answers your question, please remember to mark it as a solution.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.