DEV Community

Cover image for Build a YouTube Shorts Trend Tracker to Go Viral
Olamide Olaniyan
Olamide Olaniyan

Posted on

Build a YouTube Shorts Trend Tracker to Go Viral

YouTube Shorts is exploding.

500 million daily active users. 30 billion daily views. And creators are getting millions of views on videos they made in 5 minutes.

But here's the thing: Shorts success is all about timing and trends.

In this tutorial, we'll build a YouTube Shorts Trend Tracker that:

  1. Monitors trending Shorts in real-time
  2. Identifies viral content patterns
  3. Helps you spot trends before they blow up

Why Shorts Matter

YouTube is pushing Shorts hard:

  • Shorts get shown to non-subscribers (unlike regular videos)
  • Lower production effort = higher output
  • Algorithm rewards consistency, not perfection

The problem? Trends move fast. By the time you notice a trend manually, it's often too late.

Automation solves this.

The Stack

  • Node.js: Runtime
  • SociaVault API: To fetch trending Shorts
  • OpenAI API: For pattern analysis
  • node-cron: For automated monitoring

Step 1: Setup

mkdir shorts-trend-tracker
cd shorts-trend-tracker
npm init -y
npm install axios dotenv openai node-cron
Enter fullscreen mode Exit fullscreen mode

Create .env:

SOCIAVAULT_API_KEY=your_sociavault_key
OPENAI_API_KEY=your_openai_key
Enter fullscreen mode Exit fullscreen mode

Step 2: Fetch Trending Shorts

Let's start by getting the currently trending Shorts.

Create index.js:

require('dotenv').config();
const axios = require('axios');
const OpenAI = require('openai');
const cron = require('node-cron');

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const SOCIAVAULT_BASE = 'https://api.sociavault.com';

async function getTrendingShorts(region = 'US') {
  console.log(`πŸ“₯ Fetching trending Shorts (${region})...`);

  try {
    const response = await axios.get(`${SOCIAVAULT_BASE}/v1/scrape/youtube/shorts/trending`, {
      params: { region },
      headers: { 'Authorization': `Bearer ${process.env.SOCIAVAULT_API_KEY}` }
    });

    const shorts = response.data.data || [];
    console.log(`βœ… Found ${shorts.length} trending Shorts`);

    return shorts.map(s => ({
      id: s.id || s.videoId,
      title: s.title,
      channel: s.channelTitle || s.channel,
      views: s.viewCount || s.views,
      likes: s.likeCount || s.likes,
      published: s.publishedAt,
      thumbnail: s.thumbnail,
      duration: s.duration
    }));
  } catch (error) {
    console.error('Error fetching Shorts:', error.message);
    return [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Get Channel Shorts

To analyze what's working for specific creators:

async function getChannelShorts(channelUrl) {
  console.log('πŸ“₯ Fetching channel Shorts...');

  try {
    const response = await axios.get(`${SOCIAVAULT_BASE}/v1/scrape/youtube/channel/shorts`, {
      params: { url: channelUrl },
      headers: { 'Authorization': `Bearer ${process.env.SOCIAVAULT_API_KEY}` }
    });

    return response.data.data || [];
  } catch (error) {
    console.error('Error fetching channel Shorts:', error.message);
    return [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Search for Specific Topics

Find trending Shorts about specific topics:

async function searchShorts(query, limit = 50) {
  console.log(`πŸ” Searching Shorts for "${query}"...`);

  try {
    const response = await axios.get(`${SOCIAVAULT_BASE}/v1/scrape/youtube/search`, {
      params: { 
        query: query + ' #shorts',
        type: 'video',
        limit
      },
      headers: { 'Authorization': `Bearer ${process.env.SOCIAVAULT_API_KEY}` }
    });

    // Filter for Shorts (typically under 60 seconds)
    const videos = response.data.data || [];
    return videos.filter(v => 
      v.title?.toLowerCase().includes('#shorts') || 
      v.duration && v.duration < 62
    );
  } catch (error) {
    console.error('Error searching Shorts:', error.message);
    return [];
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Identify Trend Patterns

Use AI to spot patterns in trending content:

async function analyzeTrends(shorts) {
  console.log('πŸ€– Analyzing trend patterns...');

  const prompt = `
    Analyze these trending YouTube Shorts and identify patterns.

    Return JSON with:
    {
      "trendingTopics": [top 5 topics/themes trending right now],
      "viralFormulas": [
        {
          "formula": "description of the format/formula",
          "examples": ["example titles"],
          "whyItWorks": "explanation"
        }
      ],
      "hookPatterns": [5 attention-grabbing patterns in the first 1-3 seconds],
      "titlePatterns": [5 common title structures],
      "contentIdeas": [
        {
          "idea": "specific content idea",
          "format": "how to structure it",
          "targetViews": "estimated view potential"
        }
      ],
      "timing": "observation about posting patterns/timing"
    }

    Shorts:
    ${JSON.stringify(shorts.map(s => ({
      title: s.title,
      channel: s.channel,
      views: s.views
    })))}
  `;

  const completion = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: prompt }],
    response_format: { type: 'json_object' }
  });

  return JSON.parse(completion.choices[0].message.content);
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Track View Velocity

Identify Shorts that are growing fast:

// Store previous snapshots
const shortHistory = new Map();

function calculateVelocity(shorts) {
  const now = Date.now();
  const results = [];

  for (const short of shorts) {
    const previous = shortHistory.get(short.id);

    if (previous) {
      const timeDiff = (now - previous.timestamp) / (1000 * 60 * 60); // hours
      const viewGain = short.views - previous.views;
      const velocity = viewGain / timeDiff; // views per hour

      results.push({
        ...short,
        velocity: Math.round(velocity),
        viewGain,
        hoursSinceLastCheck: timeDiff.toFixed(1)
      });
    }

    // Store current snapshot
    shortHistory.set(short.id, {
      views: short.views,
      timestamp: now
    });
  }

  // Sort by velocity
  return results.sort((a, b) => b.velocity - a.velocity);
}

async function trackVelocity() {
  const shorts = await getTrendingShorts();
  const fastGrowing = calculateVelocity(shorts);

  if (fastGrowing.length > 0) {
    console.log('\nπŸš€ Fastest Growing Shorts:');
    fastGrowing.slice(0, 5).forEach((s, i) => {
      console.log(`\n${i + 1}. "${s.title}"`);
      console.log(`   πŸ“ˆ +${s.viewGain.toLocaleString()} views in ${s.hoursSinceLastCheck}h`);
      console.log(`   ⚑ ${s.velocity.toLocaleString()} views/hour`);
    });
  }

  return fastGrowing;
}
Enter fullscreen mode Exit fullscreen mode

Step 7: Niche Trend Detection

Focus on trends in your specific niche:

async function analyzeNiche(niche, keywords) {
  console.log(`\n🎯 Analyzing niche: ${niche}\n`);
  console.log('═══════════════════════════════════════\n');

  const allShorts = [];

  for (const keyword of keywords) {
    const shorts = await searchShorts(keyword);
    allShorts.push(...shorts);
    await new Promise(r => setTimeout(r, 500));
  }

  // Deduplicate
  const unique = allShorts.filter((s, i, self) =>
    i === self.findIndex(t => t.id === s.id)
  );

  console.log(`πŸ“Š Found ${unique.length} unique Shorts in ${niche}`);

  // Sort by views
  const sorted = unique.sort((a, b) => (b.views || 0) - (a.views || 0));

  console.log('\nπŸ† Top Performing Shorts:');
  sorted.slice(0, 10).forEach((s, i) => {
    console.log(`\n${i + 1}. "${s.title}"`);
    console.log(`   πŸ“Ί ${s.channel} | πŸ‘οΈ ${Number(s.views || 0).toLocaleString()} views`);
  });

  // Analyze the niche
  const analysis = await analyzeTrends(sorted.slice(0, 30));

  console.log('\n═══════════════════════════════════════');
  console.log('🧠 NICHE INSIGHTS');
  console.log('═══════════════════════════════════════\n');

  console.log('πŸ”₯ Trending Topics:');
  analysis.trendingTopics.forEach((t, i) => {
    console.log(`  ${i + 1}. ${t}`);
  });

  console.log('\n✨ Viral Formulas:');
  analysis.viralFormulas.forEach((f, i) => {
    console.log(`\n  ${i + 1}. ${f.formula}`);
    console.log(`     Why it works: ${f.whyItWorks}`);
    console.log(`     Example: "${f.examples[0]}"`);
  });

  console.log('\n🎣 Hook Patterns (First 1-3 seconds):');
  analysis.hookPatterns.forEach((h, i) => {
    console.log(`  ${i + 1}. ${h}`);
  });

  console.log('\nπŸ’‘ Content Ideas:');
  analysis.contentIdeas.forEach((idea, i) => {
    console.log(`\n  ${i + 1}. ${idea.idea}`);
    console.log(`     Format: ${idea.format}`);
    console.log(`     Potential: ${idea.targetViews}`);
  });

  return { shorts: sorted, analysis };
}
Enter fullscreen mode Exit fullscreen mode

Step 8: Automated Daily Reports

Set up automated trend reports:

async function generateDailyReport() {
  console.log('\nπŸ“… DAILY SHORTS TREND REPORT');
  console.log(`   ${new Date().toDateString()}\n`);
  console.log('═══════════════════════════════════════\n');

  // 1. Overall trending
  const trending = await getTrendingShorts();
  const analysis = await analyzeTrends(trending);

  console.log('🌎 GLOBAL TRENDS\n');

  console.log('Hot Topics:');
  analysis.trendingTopics.forEach((t, i) => {
    console.log(`  ${i + 1}. ${t}`);
  });

  console.log('\nWinning Formulas:');
  analysis.viralFormulas.slice(0, 3).forEach((f, i) => {
    console.log(`  ${i + 1}. ${f.formula}`);
  });

  // 2. Velocity tracking
  const fastGrowing = await trackVelocity();

  if (fastGrowing.length > 0) {
    console.log('\nπŸš€ BREAKOUT SHORTS (Growing Fast)\n');
    fastGrowing.slice(0, 5).forEach((s, i) => {
      console.log(`${i + 1}. "${s.title.substring(0, 50)}..."`);
      console.log(`   ⚑ ${s.velocity.toLocaleString()} views/hour\n`);
    });
  }

  // 3. Action items
  console.log('\nπŸ“‹ TODAY\'S ACTION ITEMS\n');
  analysis.contentIdeas.slice(0, 3).forEach((idea, i) => {
    console.log(`${i + 1}. CREATE: ${idea.idea}`);
    console.log(`   Format: ${idea.format}\n`);
  });

  return { trending, analysis, fastGrowing };
}
Enter fullscreen mode Exit fullscreen mode

Step 9: Run the Tracker

async function main() {
  // Option 1: Get today's trends
  await generateDailyReport();

  // Option 2: Analyze your niche
  // await analyzeNiche('Tech/Programming', [
  //   'coding tutorial shorts',
  //   'programming tips',
  //   'developer life',
  //   'tech shorts'
  // ]);

  // Option 3: Track a specific creator
  // const shorts = await getChannelShorts('https://youtube.com/@MrBeast');
  // console.log(`Found ${shorts.length} Shorts from MrBeast`);
}

main();

// Optional: Run every 4 hours
// cron.schedule('0 */4 * * *', generateDailyReport);
Enter fullscreen mode Exit fullscreen mode

Sample Output

πŸ“… DAILY SHORTS TREND REPORT
   Mon Jan 15 2024

═══════════════════════════════════════

πŸ“₯ Fetching trending Shorts (US)...
βœ… Found 40 trending Shorts
πŸ€– Analyzing trend patterns...

🌎 GLOBAL TRENDS

Hot Topics:
  1. AI and ChatGPT demonstrations
  2. Life hacks and productivity tips
  3. Behind-the-scenes content
  4. Satisfying/ASMR content
  5. Challenge videos and reactions

Winning Formulas:
  1. "POV: [relatable situation]" - First-person perspective storytelling
  2. "Wait for it..." - Delayed payoff/surprise ending
  3. "[Number] things that..." - List-based quick value

πŸš€ BREAKOUT SHORTS (Growing Fast)

1. "POV: You finally understand recursion"
   ⚑ 47,283 views/hour

2. "This AI tool is insane 🀯"
   ⚑ 38,921 views/hour

3. "Things your boss doesn't want you to know"
   ⚑ 31,445 views/hour

πŸ“‹ TODAY'S ACTION ITEMS

1. CREATE: POV-style video about a common frustration in your niche
   Format: First person, relatable scenario, unexpected twist

2. CREATE: "Wait for it" style with satisfying payoff
   Format: Build tension, deliver unexpected or satisfying ending

3. CREATE: Quick listicle "3 things about [topic]"
   Format: Fast-paced, text overlays, each point under 10 seconds
Enter fullscreen mode Exit fullscreen mode

Pro Tips for Going Viral

Based on what the data consistently shows:

  1. First 1 second matters - Hook immediately or people scroll
  2. Text overlays - 40% of viewers watch with sound off
  3. Loop potential - Shorts that encourage rewatching get boosted
  4. Trending audio - Using trending sounds = free distribution
  5. Post consistently - 1-3 Shorts per day outperforms sporadic posting

Get Started

  1. Get your SociaVault API Key
  2. Run the trend tracker daily
  3. Create content that matches winning patterns
  4. Track what works for YOUR audience

Stop guessing what trends. Start tracking them.

Top comments (0)