Skip to content

About

Lemmy community API for Node.js: fetch posts and comments from any Lemmy instance as typed objects, then rebuild threads, feed a moderation dashboard or forward new posts from a webhook. JavaScript example for the Devil Scrapes Apify Actor.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Lemmy Scraper — Posts, Comments & Community Data — JavaScript example

Lemmy Scraper for JavaScript and Node.js: posts and comments from any instance

Run on Apify JavaScript MIT license CI

Use this repository to read Lemmy communities from a Node.js app through the Lemmy Community Scraper. A single ES module drives Apify's official client: give it an instance URL and a community name, and it returns plain objects for each post and, if you ask, each comment, with vote counts, ActivityPub IDs, thread paths and author flags. Pagination in both of Lemmy's styles and retries on busy servers are dealt with on Apify, so a backend, a cron container or a serverless handler only starts a run and consumes rows. Running index.js from a shell also writes them to results.json and results.csv.

Actor: Lemmy Scraper — Posts, Comments & Community Data · Publisher: Devil Scrapes · Also in Python: lemmy-scraper-python

🔥 What you get

  • Any instance, any public community: point instanceUrl at lemmy.world, lemmy.ml or a niche server, and name the community either locally (asklemmy) or with its home server (memes@lemmy.world).
  • Posts and comments share one table: row_type separates them, and every comment row repeats its community and post columns, so a CSV opened on its own still says where each reply lives.
  • Thread structure kept: Lemmy's dotted comment_path is stored as is, and comment_parent_id is derived from it, so a reply can be attached to its parent without another request.
  • Sixteen sort orders: from Hot and New to time-boxed tops such as TopDay or TopYear. The old bare Top value is refused up front, since current Lemmy servers reject it.
  • Two caps you control: maxPosts limits post rows and maxCommentsPerPost limits replies per post, with separate per-row prices for each kind.
  • Errors that say what went wrong: a misspelled community fails the run with the server's own error, a run that yields nothing exits as failed, and busy-server responses are retried with backoff first.

🎯 Use cases

Mirror a community into your own app

Store posts by post_ap_id, the ActivityPub URL that stays the same on every server, and refresh them on a timer. Your frontend can then show a community's activity without hitting the instance on every page view.

Feed a moderation or brand-watch queue

Run New on a schedule, keep the post IDs you have already seen and push anything fresh into a review queue or a chat channel through a webhook. The post_nsfw and post_locked flags help route items before a human looks.

Render threads in a React or Vue view

The recipe below turns flat comment rows into nested reply trees. Ship that JSON to a component and you have a read-only thread viewer without writing a Lemmy client.

Cross-post digests to other platforms

A serverless function can take the week's top posts from TopWeek, format title, score and link, and publish a digest to Discord, Matrix or a newsletter tool.

⚡ Quick start

You need an Apify account and an API token from Console → Settings → Integrations. Apify's free plan includes monthly usage credit; this Actor's event prices are listed under Pricing below.

git clone https://github.com/devilscrapes/lemmy-scraper-javascript.git
cd lemmy-scraper-javascript
npm install
export APIFY_TOKEN=your_token_here
node index.js                       # uses input.json
node index.js my-input.json --out data --max-charge 2

The script starts the Lemmy Scraper — Posts, Comments & Community Data, waits for it to finish, prints a link to the run in Apify Console and saves every result to results.json and results.csv. It exits with code 1 and the run's status message if the run fails.

🧩 The core call

This is the complete integration. call() returns after the run ends, and listItems() hands you its rows from the default dataset.

import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });
const run = await client.actor('DevilScrapes/lemmy-community-scraper').call({"instanceUrl": "https://lemmy.world", "communityName": "asklemmy", "sort": "TopWeek", "maxPosts": 3, "includeComments": true, "maxCommentsPerPost": 2});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items);

📥 Input

index.js sends input.json as written. It asks lemmy.world for this week's top three asklemmy posts and two replies on each, which keeps a trial run to nine rows or fewer. Any value in the sort column of the table below is accepted.

{
  "instanceUrl": "https://lemmy.world",
  "communityName": "asklemmy",
  "sort": "TopWeek",
  "maxPosts": 3,
  "includeComments": true,
  "maxCommentsPerPost": 2
}
Field Type Required Default Allowed values
instanceUrl string yes "https://lemmy.world" —
communityName string yes "asklemmy" —
sort string no "Hot" Active, Hot, New, Old, Scaled, Controversial, MostComments, NewComments, TopHour, TopSixHour, TopTwelveHour, TopDay, TopWeek, TopMonth, TopYear, TopAll
maxPosts integer no 100 —
includeComments boolean no false —
maxCommentsPerPost integer no 50 —
useProxy boolean no false —

📤 Output

Expect a mix of post objects and comment objects in one array; filter on row_type. Every comment object repeats its post's fields, which costs bytes but means a single row is enough to render a reply with its context.

Field Type Always present
row_type string yes
instance_url string yes
community_actor_id string yes
community_name string yes
community_title string yes
community_description string or null no
community_subscribers integer yes
community_posts_count integer yes
community_local boolean yes
post_id integer yes
post_ap_id string yes
post_url string yes
post_title string yes
post_body string or null no
post_external_url string or null no
post_score integer yes
post_upvotes integer yes
post_downvotes integer yes
post_comments_count integer yes
post_published string yes
post_updated string or null no
post_nsfw boolean yes
post_featured_community boolean yes
post_locked boolean yes
comment_id integer or null no
comment_ap_id string or null no
comment_path string or null no
comment_content string or null no
comment_score integer or null no
comment_published string or null no
comment_parent_id integer or null no
author_actor_id string yes
author_name string yes
author_display_name string or null no
author_bot_account boolean yes
author_published string yes
scraped_at string yes

💰 Pricing

Event Price (USD)
Post row emitted $0.002
Comment row emitted $0.001

Prices as configured on 2026-11-03. The Actor page always shows the current price. Runs are billed to the Apify account that owns the token. Use --max-charge to cap what a single run can cost.

🛠️ Working with the data in JavaScript

Here is a built-ins-only script that rebuilds each post's discussion as a nested tree, saves it to threads.json and prints a one-line summary per post. Replies whose parent fell outside your comment cap are attached to the post so nothing is dropped.

import { readFile, writeFile } from 'node:fs/promises';

const rows = JSON.parse(await readFile('results.json', 'utf8'));
const threads = new Map();
for (const p of rows.filter((r) => r.row_type === 'post')) {
    threads.set(p.post_id, { id: p.post_id, title: p.post_title, url: p.post_url, score: p.post_score, replies: [] });
}

const comments = rows.filter((r) => r.row_type === 'comment');
const nodes = new Map(comments.map((c) => [c.comment_id, { id: c.comment_id, score: c.comment_score, text: c.comment_content, replies: [] }]));
for (const c of comments) {
    // a reply whose parent was cut by maxCommentsPerPost hangs off the post instead
    const parent = (c.comment_parent_id !== null && nodes.get(c.comment_parent_id)) || threads.get(c.post_id);
    parent?.replies.push(nodes.get(c.comment_id));
}

await writeFile('threads.json', JSON.stringify([...threads.values()], null, 2));
const size = (node) => node.replies.reduce((n, child) => n + 1 + size(child), 0);
for (const t of threads.values()) console.log(`${String(t.score).padStart(5)}  ${size(t)} comments  ${t.title}`);

❓ FAQ

Why does the same post have different IDs on different instances?

post_id is local to the server you queried. Use post_ap_id when you merge data from several instances, because the ActivityPub URL is shared across the federation.

Can my API route wait for the run to finish?

For a handful of posts, yes. Larger pulls with comments make one request per comment page, so start them with start() and let an Apify webhook notify your service when the dataset is ready.

Which sort should a feed use?

New for a stream of the latest posts, Active or Hot for what people are discussing, and a Top* value for digests. Each time-boxed top token covers a fixed window, from an hour to all time.

Is it fine to run this from TypeScript?

Yes. The Apify client publishes typings, so the call compiles unchanged. A discriminated union on row_type models post and comment rows cleanly.

🧯 Troubleshooting

  • Set APIFY_TOKEN first: export the token in the same shell, or put it in a local .env file your shell loads. Never commit it.
  • Run finished with FAILED or ABORTED: open the printed Console link; the run log says why. Input validation errors name the field.
  • Fewer rows than expected: a --max-charge cap also limits how many results can be charged. Raise the cap or lower the limits in your input.
  • Something looks wrong in the data: open an issue on the Actor page so the maintainers see it.

🔗 More from Devil Scrapes

Related Actors:


MIT licensed example code. The Actor itself runs on Apify and is maintained by Devil Scrapes. Not affiliated with the Lemmy project or any Lemmy instance.

About

Lemmy community API for Node.js: fetch posts and comments from any Lemmy instance as typed objects, then rebuild threads, feed a moderation dashboard or forward new posts from a webhook. JavaScript example for the Devil Scrapes Apify Actor.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages