DEV Community

Cover image for How to get the count of your followers on dev.to
tq-bit
tq-bit

Posted on • Updated on • Originally published at blog.q-bit.me

How to get the count of your followers on dev.to

Note: There's a PR on the Forem repo open for this. Check out if it has been implemented before trying this!

Fortunately, Forem ships with a REST API. At the time of writing this article, it did not support the follower count for the active user natively. For you as a developer, this should be no obstacle to calculating them yourself.

Setting up the project

Prepare the project directory

This project will consist of a single "index.js" file that you can deploy anywhere. I recommend using an Nginx reverse proxy and pm2 to keep the service running.

  1. Change into a directory of your choice and initialize a new NPM project.
  2. Install "express" and "axios"
cd /path/to/project
touch index.js
npm init -y
npm i express axios 

Enter fullscreen mode Exit fullscreen mode

Generate a dev.to API token

Head over to your dev.to profile and create an API key. The option is at the bottom of the page.

  1. Enter a name for your key
  2. Click on "Generate API key"
  3. Copy it to the clipboard
  4. Head over to val.town secrets.
  5. Create an entry with the name "DEVTO_API_KEY"
  6. Paste your API key into the value field

Add some boilerplate

Add the following code to your index.js file. Make sure to update the API_TOKEN with your secret. Even better: Use the dotenv NPM package to keep your code free of secret keys.

const express = require('express');
const axios = require('axios');
// You can request a token here: https://dev.to/settings/extensions (scroll down to bottom)
const API_TOKEN = 'super-secret';
const CACHE_LIFETIME = 1000 * 60 * 60 * 4; /* 4 hours */
const PORT = 3000;

const app = express();
let cache = {
    followers: {
        count: 0,
        entries: [],
    },
};

const gatherFollowerCount = async () => {
    cache.followers.count += 1;
};

// Interval to update cache
setInterval(() => {
    console.log('Updating cache');
    gatherFollowerCount();
}, CACHE_LIFETIME);

app.get('/', (req, res) => {
    res.send({ followers: cache.followers.count });
});

app.listen(PORT, () => {
    gatherFollowerCount();
    console.log('Listening on port ' + PORT);
});

Enter fullscreen mode Exit fullscreen mode

Then, run it:

node index.js

Enter fullscreen mode Exit fullscreen mode

This piece of code

  • Create an express server on port 3000
  • Maintains an in-memory cache for your followers
  • Updates this cache every 4 hours using the "gatherFollowerCount" function
  • Sends the cache to a client requesting it on the root path

⚠️ Stay fair, don't overuse the API!

Every API call you make causes traffic, which in turn costs money. If you have a lot of followers, the sum of your requests might be huge. In this case, please adjust your cache lifetime to a higher value.

If you're beyond the 10k, please also consider implementing a queue for your API requests with a generous delay in between

Visit http://localhost:3000 in your browser to check if everything works as expected.

Calculate your follower count

Add the following to the "gatherFollowerCount" function.

const gatherFollowerCount = async () => {
    const perPage = 100;
    let page = 0;

    const fetchFollowers = async () => {
        const url = `https://dev.to/api/followers/users?page=${page}&per_page=${perPage}`;

        const response = await axios.get(url, {
            headers: {
                'api-key': API_TOKEN || '',
            },
        });

        cache.followers.entries = [...response.data, ...cache.followers.entries];
        cache.followers.count = cache.followers.entries.length;

        if (response.data.length === perPage) {
            page++;
            await fetchFollowers();
        }
    };

    await fetchFollowers();
};

Enter fullscreen mode Exit fullscreen mode

This code

  • recursively gathers all followers from the dev.to API
  • adds them to your cache
  • and updates the follower count

Restart the server and check http://localhost:3000. You should see your follower count in the browser now, ready to be implemented for your personal blog or portfolio.

PS: You can apply the same practice to other dev.to stats that might not yet be part of the official API.

Top comments (4)

Collapse
 
ingosteinke profile image
Ingo Steinke, web developer

Nice work, but I like that DEV doesn't display follower count in a prominent place. Likewise, likes should also be shown less quantitatively and focus more on quality. This is not Twitter.

Collapse
 
tqbit profile image
tq-bit

You're absolutely right. I wouldn't want to display it anywhere except for a portfolio page, where it might be relevant for future clients or employers.

Like this:
Image description

Collapse
 
cicirello profile image
Vincent A. Cicirello

@tqbit showing your follower count on your portfolio isn't particularly meaningful. I get around 100 or so new "followers" daily, sometimes more if I've posted recently. However, I'd say at least 10% of them are spam accounts, and very obviously so (e.g., user id and name blatantly advertising casinos, travel agencies, etc, or you go to their profile and all of their posts are spam). Even if DEV disables a spammer's account, they appear to remain in your list of followers.

Thread Thread
 
tqbit profile image
tq-bit

Great of you to point this out. I hope you don't mind I've added your comment under the official PR for consideration,