Strapi: Exposing custom user data in users /me endpoint

If you don’t know about Strapi, It is a powerful and popular NodeJS headless CMS that was built with the aim to “Design APIs fast, manage content easily”.

On its ‘users/me’ endpoint, it returns sanitized user info without any related data. If you need additional related data to be exposed, you have to override the ‘me’ function manually. For this, you have to create a file in a specific folder and create a new function with the same name.

File location: extensions/users-permissions/controllers/User.js

File content:

const { sanitizeEntity } = require('strapi-utils');

const sanitizeUser = user =>
  sanitizeEntity(user, {
    model: strapi.query('user', 'users-permissions').model,
  });

module.exports = {
  async me(ctx) {
    const user = ctx.state.user;

    if (!user) {
      return ctx.badRequest(null, [{ messages: [{ id: 'No authorization header was found' }] }]);
    }

    const userQuery = await strapi.query('user', 'users-permissions');
    const userWithMedia = await userQuery.findOne({ id: ctx.state.user.id });

    const data = sanitizeUser(userWithMedia, { model: userQuery.model });
    ctx.send(data);
  },
};

This will return all related fields. Feel free to modify according to your needs. Happy Strapi-ing.. 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.