Using Strapi as a multi-tenant

Hi @TristanTrvl great question. You can achieve this by overriding the default controller in the ./api/model_name/controllers/model_name.js file. The controller you’re looking for is called create. If you create a new async function called create inside the exported object, you have access to the ctx parameter on that function. This param contains information about the request that has been made to this controller. On this ctx object you will have a state parameter that among other things, will have a property called user set to the user that is making the request if they are authenticated while making the request. You can fetch the id on that user object and set it to the tenant_id field on your content type.

Here’s an example:
I have a model called Item and it has two fields, name and user. I populate the user field in the manner I’ve described above.

"use strict";
const { sanitizeEntity } = require("strapi-utils"); // this function removes all private fields from a model and it's relations

module.exports = {
  async create(ctx) {
    let entity = await strapi.services.item.create({
      ...ctx.request.body, // the user is always on the context state object when an authenticated request is made
      user: ctx.state.user,
    }); // strapi.services.item.create uses the auto-generated create service for this model to create the entity
    return sanitizeEntity(entity, { model: strapi.models.item }); // return the sanitized entity always
  },
};

1 Like