For the rest of this article, I will assume you already know about Prisma and how it works. If you don’t, Prisma is a really awesome library that replaces traditional ORMs. I strongly suggest you discover it and follow the getting started tutorial.
A Prisma service is defined by a GraphQL datamodel and a name/stage identification. Prisma servers can be configured to host multiple Prisma services.
Each Prisma service has exactly one endpoint, composed of the server host, service name and the service stage.
If you do not provide a service name or stage, they will be both assigned the value “default”.
To use Prisma services for a multi-tenant application, we can deploy the same GraphQL datamodel to multiple services.
Starting our app with a single tenant
As an illustration, we’re going to take our previous example: Slack. Let’s then start with our datamodel and create an User and a Post:
Then, deploy your datamodel to
We should now have a service ready for our application. Let’s write the server:
If you run your server, you should be able to query the users from the
companya/dev service. That’s a great start but as we’ve hardcoded our client’s service in our server, adding a new tenant wouldn’t be easy.
Evolving into a multi-tenant app
In order to make our server multi-tenant, we will use the prisma-multi-tenant package.
npm install prisma-multi-tenant
Then, redeploy your datamodel to two more services:
Finally, we will change our server file to the following:
As you can see, we created a
MultiTenant object, and used its
current method in the context option of ApolloServer. We also did not change our resolvers, as if we were still dealing with a single tenant.
Now, when you query your server, add the
prisma-service HTTP header with the name/stage of the service you want to access (“company_a/prod” for example), and it will query the right service.
Aaand, that’s it. You’ve got a multi-tenant server.
“Wait… That’s all we have to do? Using a library and querying with an HTTP header? Really?”
We haven’t written a Slack-like application, but yes, this is the foundation of your multi-tenant application. Prisma is dealing with multiple database, and your server won’t care which. It will just work. Moreover, your server can now be deployed once, and handle requests coming from any tenants!