Search code examples
next.jsstrapinext-auth

Get content related to a user in Strapi


I have a collection in Strapi called projects and I want to be able to fetch only the projects belonging to the currently logged in user. I'm using Next.js with NextAuth on the frontend and I'm currently filtering the results using:

/api/projects?filters[user][id][$eq]=${session.id}

This works fine except the endpoint still allows a user to fetch projects for all users if accessed directly. I'm thinking a better approach would be to setup a custom API endpoint in Strapi which would be something like /api/projects/:user. Is this the best way to acheive this? I've managed to setup a custom endpoint in Strapi using the CLI but I'm not sure what logic needs to go in the controller. Would modifiying an exisiting endpoint be better?

Any advice appreciated, thanks!


Solution

  • I ended up extending my controller. In src/api/controllers/project.js I made the following changes:

    "use strict";
    
    const { createCoreController } = require("@strapi/strapi").factories;
    
    module.exports = createCoreController("api::project.project", {
    
      async find(ctx) {
        const user = ctx.state.user;
        ctx.query.filters = {
          ...(ctx.query.filters || {}),
          user: user.id,
        };
        return super.find(ctx);
      },
    });
    

    Then simply call the /api/projects endpoint.

    Answer based on this guide Limit access of Strapi users to their own entries.