How to create followers/following functionality in Strapi

Hey everyone, so I am primarily a frontend dev, I am planning to do a social media app (similar to instagram) and I am using Strapi in the backend to create API’s.

So my question is, I wanted to create a followers/following type of functionality and I’m stuck on how to implement the relationships and stuffs! So can someone please explain me how to do it

Check out youtubes about basic strapi. When you start new strapi you basically have almost all you need. You have collection type “users” all you have to do is add new relation back to “users” and select one-to-many/relations. You do that 2 times ones for followers once for following.

Firstly, you’ll need two tables, say ‘Followers’ and ‘Following’. Both tables will have ‘UserID’ and ‘FollowerID’ or ‘FollowingID’ columns. When a user follows another, you insert a row into each table to create the relationship.

For real-time functionality, consider implementing a socket or a pub/sub pattern. This will make it easier to notify users instantly when someone follows them.

If you want to automatically boost the visibility of posts to new followers, you could also consider integrating a feature like auto-likes, similar to how you can Buy Tik Tok auto likes. By automatically liking new posts, you could drive more engagement and make the platform more appealing for your users.

User Model:
Ensure you have a user model in Strapi to represent users. If you don’t have one, you may need to create it. You can include fields like username, email, and any other relevant user information.

Follower/Following Model:
Create a new model for managing the follower/following relationships. This model should have two fields, one for the follower (a reference to the User model) and another for the user being followed (another reference to the User model).

Create APIs:
Generate APIs for your User and Follower/Following models in Strap. These APIs will provide the necessary endpoints for interacting with user data and managing relationships.

User Registration and Authentication:
Implement user registration and authentication functionality. Strap offers user authentication and registration features out of the box. Make sure your users are authenticated before they can follow or be followed.

i don’t understand :smiling_face_with_tear:

Your approach is optimal from a data normalization point of view, but the main problem occurring here is, that we can get pagination data of followers but not following, so if the front-end guy needs pagination for following then it’s a bad choice.

That’s a good choice however we are storing twice the data. So is there any alternative approach?

Hey there!

Creating a followers/following functionality in Strapi involves setting up relationships between your user model and creating the necessary logic to manage these relationships. Here’s a step-by-step guide to help you implement this:

Step 1: Define User Model

Ensure you have a User model. Strapi provides a default User model if you have the Users & Permissions plugin installed.

Step 2: Add Relationships

You need to add self-referencing many-to-many relationships to the User model for followers and following.

  1. Navigate to Content-Types Builder:
  • Go to Strapi’s admin panel.
  • Click on Content-Types Builder.
  1. Modify the User Model:
  • Select the User model.
  • Add a new field for followers:
    • Field Name: followers
    • Field Type: Relation
    • Relation: User → Many-to-Many → User
  • Add another new field for following:
    • Field Name: following
    • Field Type: Relation
    • Relation: User → Many-to-Many → User
  1. Save and Restart:
  • Save your changes and restart Strapi to apply the changes.

Step 3: Create Endpoints

You need to create custom endpoints to handle the follow and unfollow actions.

  1. Create a Custom Controller:
  • In your Strapi project, navigate to ./api/user/controllers.
  • Create a new file named customUser.js.
  1. Implement Follow/Unfollow Logic:
  • Add the following code to customUser.js:

javascript

Copy code

module.exports = {
  async follow(ctx) {
    const { userId, followId } = ctx.request.body;

    if (!userId || !followId) {
      return ctx.badRequest('User ID and Follow ID are required.');
    }

    const user = await strapi.query('user', 'users-permissions').findOne({ id: userId });
    const followUser = await strapi.query('user', 'users-permissions').findOne({ id: followId });

    if (!user || !followUser) {
      return ctx.notFound('User not found.');
    }

    await strapi.query('user', 'users-permissions').update({ id: userId }, {
      following: [...user.following, followId]
    });

    await strapi.query('user', 'users-permissions').update({ id: followId }, {
      followers: [...followUser.followers, userId]
    });

    return ctx.send({ message: 'Followed successfully.' });
  },

  async unfollow(ctx) {
    const { userId, followId } = ctx.request.body;

    if (!userId || !followId) {
      return ctx.badRequest('User ID and Follow ID are required.');
    }

    const user = await strapi.query('user', 'users-permissions').findOne({ id: userId });
    const followUser = await strapi.query('user', 'users-permissions').findOne({ id: followId });

    if (!user || !followUser) {
      return ctx.notFound('User not found.');
    }

    await strapi.query('user', 'users-permissions').update({ id: userId }, {
      following: user.following.filter(id => id !== followId)
    });

    await strapi.query('user', 'users-permissions').update({ id: followId }, {
      followers: followUser.followers.filter(id => id !== userId)
    });

    return ctx.send({ message: 'Unfollowed successfully.' });
  }
};

Step 4: Create Routes

You need to create routes for the follow and unfollow actions.

  1. Create a Custom Route:
  • In your Strapi project, navigate to ./api/user/config/routes.json.
  1. Add Routes for Follow/Unfollow:
  • Add the following routes to routes.json:

json

Copy code

{
  "routes": [
    {
      "method": "POST",
      "path": "/users/follow",
      "handler": "customUser.follow",
      "config": {
        "policies": []
      }
    },
    {
      "method": "POST",
      "path": "/users/unfollow",
      "handler": "customUser.unfollow",
      "config": {
        "policies": []
      }
    }
  ]
}

Step 5: Test Your Endpoints

Now you can test your follow and unfollow endpoints using a tool like Postman or directly in your frontend.

  • Follow Endpoint:
    • URL: http://localhost:1337/users/follow
    • Method: POST
    • Body: { "userId": "USER_ID", "followId": "FOLLOW_ID" }
  • Unfollow Endpoint:
    • URL: http://localhost:1337/users/unfollow
    • Method: POST
    • Body: { "userId": "USER_ID", "followId": "FOLLOW_ID" }

This should get you started with implementing followers/following functionality in your social media app using Strapi. Let me know if you need any further assistance!