Home > Back-end >  How to identify the tenant in a multi-tenant application using React?
How to identify the tenant in a multi-tenant application using React?

Time:02-02

I'm building a multi-tenant application with a React.js frontend and Laravel API. When the user logs in, I add the tenant_id to their session. When a request is made from the frontend, I plan to use a middleware that gets the tenant_id from the user's session, and attach it to the request query as a url param (e.g. api.com?tenant_id=xxx), then call next() to continue with the request.

Directly after, I'll call the InitializeTenancyByRequestData middleware from the tenancy-for-laravel package, that will scope the user to the correct tenant database schema based on the tenant_id attached to the url in the previous middleware.

Is storing the tenant_id in session data secure? And is this overall approach a reasonable way to go about multi-tenancy using multiple schemas with a SPA frontend and API?

CodePudding user response:

Storing the tenant_id in session data is generally considered secure as long as the session is properly secured using encryption and secure cookie flags. However, there is always a risk of session hijacking, so it is important to take appropriate measures such as using secure communication channels and regularly rotating the encryption keys used to secure the session.

As for your approach, it seems reasonable and commonly used for multi-tenancy with a SPA frontend and API. By scoping the user to the correct tenant database schema, you can ensure that each tenant only sees the data that is relevant to them. The middleware pattern you described is a good way to attach the tenant_id to each request, making it easy to access and use throughout your application. However, keep in mind that this approach may have performance implications if your tenant data grows significantly, as each request will have to switch to a different schema. Consider caching or indexing strategies to mitigate this.

  • Related