A minimal scraping serverless API that returns trending videos based on a query, sorted by view count in descending order.
This is a Next.js API, it uses zero external dependencies outside of Next itself. The entire API is contained within api/search/route.ts
, making it easy to plug into existing projects.
- An
/api/search
endpoint that scrapes YouTube search results - Returns
JSON
with title, link, channel, thumbnail, and views - In-memory cache speeds up repeated requests
- Configurable settings for cache TTL and min/max result limit
- A
GET
request is made to/api/search
with a search term. - The server checks the in-memory cache; if a result exists, it returns cached data.
- If no cache, it scrapes the YouTube search results page, extracts embedded
JSON
(ytInitialData
), parses video info, and sorts by view count. - The result is cached and sent back as a
JSON
response.
Query parameters:
q
: Search termlimit
(optional): Number of results (defaults to 1, maximum defaults to 4, all configurable)
Example local request using curl
:
curl "http://localhost:3000/api/search?q=lofi&limit=4"
Example response:
{
"videos": [
{
"title": "Lofi Chill Beats",
"link": "https://www.youtube.com/watch?v=abc123",
"channel": "Lofi Girl",
"thumbnail": "https://i.ytimg.com/vi/abc123/hqdefault.jpg",
"views": 1250000
},
...
]
}
Returned fields:
title
: Video title textlink
: Full YouTube video URLchannel
: Uploader’s namethumbnail
: Thumbnail image URLviews
: View count as number
Config variables can be found at the start of route.ts
:
// Query limiting
const DEFAULT_LIMIT = 1;
const MAX_LIMIT = 4;
// Caching
const CACHE_TTL = 12 * 60 * 60 * 1000; // 12 hours
Clone the repository:
git clone https://github.com/yourusername/yt-trend-scraper-api.git
cd yt-trend-scraper-api
Install dependencies:
npm install
Test the development server
npm run dev
Test http://localhost:3000/search?q=test
to verify it’s running.
This project is licensed under the MIT License. See the LICENSE file for more information.