<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marco Esposito on Medium]]></title>
        <description><![CDATA[Stories by Marco Esposito on Medium]]></description>
        <link>https://medium.com/@espositomarco?source=rss-7c91ffa1ffda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N_Ec7k6y1QKhrV-C4D1N4A.jpeg</url>
            <title>Stories by Marco Esposito on Medium</title>
            <link>https://medium.com/@espositomarco?source=rss-7c91ffa1ffda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:42:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@espositomarco/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handle Multi Tenant, multi db, with NestJS and TypeORM]]></title>
            <link>https://espositomarco.medium.com/handle-multi-tenant-multi-db-with-nestjs-and-typeorm-ee50f162485e?source=rss-7c91ffa1ffda------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee50f162485e</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[multi-tenant]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typeorm]]></category>
            <dc:creator><![CDATA[Marco Esposito]]></dc:creator>
            <pubDate>Thu, 28 May 2020 22:19:59 GMT</pubDate>
            <atom:updated>2020-05-29T09:20:22.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tl0T398R5hVntAuZghVUzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*H-mbMzd_8HgblPZb_KlPvw.png" /><figcaption><a href="https://nestjs.com/">NestJS</a> — <a href="https://typeorm.io/#/">TypeORM</a></figcaption></figure><p>Hi, my name is Marco Esposito. I’ve been working as full-stack developer at <a href="https://www.justweb.it/"><em>Justweb</em></a> for the past 12 years. Developing web applications using Angular + Typescript. When I first found out of NestJS I was impressed, writing the code with same terms as Angular with Modules, Components, Services, Pipes, etc and in Typescript was absolutely amazing! So I decided to give it a go, and it was love at first sight!</p><p>Today we will build a server with NestJS and TypeORM that will handle multi tenant, with multi database, requests.</p><h4>Generate Application</h4><p>Let’s start using the nest CLI to generate our app</p><pre>$ npm i -g @nestjs/cli<br>$ nest new multi-tenant</pre><p>Follow the instructions and you will end up with something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*IgqfmRG3RUwQ2kcnVQ9zjA.png" /></figure><p>Run your application using the following command, this will re-build on changes</p><pre>$ yarn start:dev</pre><p>Go to your browser and navigate to http://localhost:3000/ and you will see the <em>Hello World!</em> screen</p><h4>TypeORM Integration</h4><p>We can now add TypeORM to our project</p><pre>$ yarn add @nestjs/typeorm typeorm mysql</pre><p>Now we can import <em>TypeOrmModule</em> into <em>AppModule. </em>You can also use ormconfig.json file in the root of your app for configuration, but we will pass it in the forRoot method.</p><pre><em>import </em>{ Module } <em>from </em>&#39;@nestjs/common&#39;;<br><em>import </em>{ TypeOrmModule } <em>from </em>&#39;@nestjs/typeorm&#39;;<br><br><em>import </em>{ AppController } <em>from </em>&#39;./app.controller&#39;;<br><em>import </em>{ AppService } <em>from </em>&#39;./app.service&#39;;<br><br>@Module({<br>  imports: [<br>    TypeOrmModule.<em>forRoot</em>({<br>      type: &#39;mysql&#39;,<br>      host: &#39;localhost&#39;,<br>      port: 3307,<br>      username: &#39;root&#39;,<br>      password: &#39;root&#39;,<br>      database: &#39;test&#39;,<br>      entities: [],<br>      synchronize: <em>true</em>,<br>    }),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br><em>export class </em>AppModule {}</pre><h4>Tenant Module</h4><p>In this module we will generate and handle the different connection for the tenants.</p><pre>$ nest generate module tenant</pre><p>First thing is to add a middleware to intercept every request. In this example I will you use the default connection to find the correct Tenant for the request and use it to check if we already have a registered connection for it or we need to generate one. Of course you can use different methods to evaluate what Tenant you need, I’m using a DB where I have stored the Tenants data.</p><pre>configure(<em>consumer</em>: <em>MiddlewareConsumer</em>): <em>void </em>{<br>  <em>consumer<br>    </em>.apply(<em>async </em>(<em>req</em>, <em>res</em>, <em>next</em>) =&gt; {<br><br>      <em>const </em>tenant: Tenant = <em>await this</em>.connection.getRepository(Tenant).findOne(({ where: { host: <em>req</em>.headers.host } }));<br><br>      <em>if </em>(!tenant) {<br>        <em>throw new </em>BadRequestException(<br>          &#39;Database Connection Error&#39;,<br>          &#39;There is a Error with the Database!&#39;,<br>        );<br>      }<br><br>      <em>try </em>{<br>        getConnection(tenant.name);<br>        <em>next</em>();<br>      } <em>catch </em>(<em>e</em>) {<br><br>        <em>const </em>createdConnection: Connection = <em>await </em>createConnection({<br>          name: tenant.name,<br>          type: &quot;mysql&quot;,<br>          host: &quot;localhost&quot;,<br>          port: 3307,<br>          username: &#39;root&#39;,<br>          password: &#39;root&#39;,<br>          database: tenant.name,<br>          entities: [ ],<br>          synchronize: <em>true</em>,<br>        })<br><br>        <em>if </em>(createdConnection) {<br>          <em>next</em>();<br>        } <em>else </em>{<br>          <em>throw new </em>BadRequestException(<br>            &#39;Database Connection Error&#39;,<br>            &#39;There is a Error with the Database!&#39;,<br>          );<br>        }<br>      }<br>    }).forRoutes(&#39;*&#39;);<br>}</pre><p>Also in the TenantModule we will need to add and export a Factory provider that will be used in the services to inject the connection. This will have a scope type REQUEST</p><blockquote><em>Scope REQUEST: A new instance of the provider is created exclusively for each incoming request. The instance is garbage-collected after the request has completed processing.</em></blockquote><pre>providers: [<br>  {<br>    provide: <strong><em>TENANT_CONNECTION</em></strong>,<br>    inject: [<br>      <strong><em>REQUEST</em></strong>,<br>      Connection,<br>    ],<br>    scope: Scope.<em>REQUEST</em>,<br>    useFactory: <em>async </em>(<em>request</em>, <em>connection</em>) =&gt; {<br>      <em>const </em>tenant: Tenant = <em>await connection</em>.getRepository(Tenant).findOne(({ where: { host: <em>request</em>.headers.host } }));<br>      <em>return </em>getConnection(tenant.name);<br>    }<br>  }<br>],<br>exports: [<br>  <strong><em>TENANT_CONNECTION<br></em></strong>]</pre><p>Let’s create now a decorator that will be used on the services that will need a tenant connection. This decorator also will have a scope type REQUEST</p><pre><em>import </em>{ applyDecorators, Injectable, Scope } <em>from </em>&#39;@nestjs/common&#39;;<br><br><em>export const </em>TenantService = () =&gt;<br>  applyDecorators(<br>    Injectable({ scope: Scope.<em>REQUEST </em>})<br>  );</pre><h4>Implementation of a Module that will use a Tenant connection</h4><p>Now we will generate a Module, a Controller, a Service and a Entity that will use a Tenant connection.</p><pre>$ nest generate module books<br>$ nest generate controller books<br>$ nest generate service books</pre><p>In the service we will add the TenantService decorator so it will use a scope type REQUEST. We will inject the TENANT_CONNECTION and will use the connection to fetch all the books</p><pre>@TenantService()<br><em>export class </em>BooksService {<br><br>  <em>constructor</em>(@Inject(<strong><em>TENANT_CONNECTION</em></strong>) <em>private </em>connection) { }<br><br>  <em>async </em>findAll(): <em>Promise</em>&lt;Book[]&gt; {<br>    <em>const </em>repository = <em>await this</em>.connection.getRepository(Book);<br>    <em>return </em>repository.find();<br>  }<br>}</pre><p>All the request to this Service will have the correct tenant connection. And from that connection you can get the repository of your Entity.</p><h4>Try it on local machine</h4><p>To try different tenants on your local machine edit your <em>hosts </em>file</p><pre>127.0.0.1 tenant1.local tenant2.local</pre><h4>Conclusion</h4><p>We saw how we can have a NestJS server that handles multi tenant, with multi db. And how to test it on the local machine.</p><p>We used a Middleware, a Factory provider and a Decorator to achive our goal. And now every other service that will need a tenant connection can be implemented easly.</p><p>I hope this helped you, and if you have any questions or other approches to this problem let me know!</p><p>Here you can find the repository containing the working project</p><p><a href="https://github.com/marcoesposito/nestjs-typeorm-multi-tenant">marcoesposito/nestjs-typeorm-multi-tenant</a></p><p>For NestJS documentation</p><p><a href="https://docs.nestjs.com/">Documentation | NestJS - A progressive Node.js framework</a></p><p>For TypeORM documentation</p><p><a href="https://typeorm.io/">TypeORM - Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.</a></p><p>A special thanks to <a href="https://medium.com/u/899f3e7023fb">Giovanni Vinaccia</a> for helping me out with this!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee50f162485e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>