# Multi-tenancy

If you need to handle multi-tenancy in your new application, you can just reply with `yes` when you are being prompted about this topic at the beginning and voilà! Everything will be done for you.

This feature comes with a middleware function that identifies the tenant on every request using different strategies.&#x20;

By default it first looks for the *tenantId* in the query string ( `request.query.tenantId` ), if not there then we'll decode the token and try to extract it from there.&#x20;

You can use other strategies of tenant identification, we also included some you can choose from or you can define your own.

```javascript
const tenantIdentification = () => async (ctx, next) => {
    if (!ctx.tenant) {
        const tenantId = R.ifElse(
            getTenantIdFromQueryString,
            getTenantIdFromJwt
        )(ctx)

        ctx.tenant = await tenantFactory.getTenantFromId(tenantId);
    }
    await next();
}

const getTenantIdFromJwt = ({ token }) => {
    let tenantId = null;
    if (token) {
        const decoded = jsonwebtoken.decode(token.replace("Bearer ", ""));
        if (decoded) {
            tenantId = decoded.tid;
        }
    }
    return tenantId;
}
const getTenantIdFromQueryString = ({ request }) => request.query.tenantId

const getTenantIdFromHeaders = ctx => ctx.req.headers.tenantid

const getTenantIdFromHost = ctx => ctx.hostname

const getTenantIdFromRefererHost = async ctx => {
    if (!ctx.request.headers.referer) {
        return;
    }
    var url = new URL.parse(ctx.request.headers.referer);
    return url.hostname
};
```

In addition, when choosing this option, you will find a `src/features/tenant` folder. This contains the infrastructure (query, resolvers, dataLoaders and api functions) you can use to manage multi-tenancy in your front-end application.&#x20;

{% hint style="info" %}
This is the missing piece for the **Tenant Selector** component, a part of the [Webapp Rocket Generator -> Multi-tenancy](https://github.com/osstotalsoft/generator-webapp-rocket#multi-tenancy).
{% endhint %}

When generating a multi-tenant application you are prompted with the following database questions:

* Use shared database (yes/no). In case multiple tenants share the same database, the tables will be filtered by a 'tenant id' column
* Database connection name. The connection information (server, database, user, password, etc.) will found in the tenant configuration under this name
