Skip to content

Instantly share code, notes, and snippets.

@ahmedsayedabdelsalam
Last active August 16, 2023 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedsayedabdelsalam/ee093a934d0b149b19790fa715f86ce2 to your computer and use it in GitHub Desktop.
Save ahmedsayedabdelsalam/ee093a934d0b149b19790fa715f86ce2 to your computer and use it in GitHub Desktop.
tenancy-livewire
export default function(tenant, headerKey = 'X-Tenant') {
handleLivewireCalls(tenant, headerKey)
handleFetchCalls(tenant, headerKey)
handleXMLHttpCalls(tenant, headerKey)
handleAxiosCalls(tenant, headerKey)
}
function handleLivewireCalls(tenant, headerKey) {
if (! window.Livewire) return;
window.Livewire.connection.headers = {
...window.Livewire.connection.headers,
[headerKey]: tenant
};
}
function handleFetchCalls(tenant, headerKey) {
const { fetch: originalFetch } = window;
window.fetch = async (...args) => {
let [resource, config = {} ] = args;
config.headers = {
...config.headers,
[headerKey]: tenant
}
return await originalFetch(resource, config);
};
}
function handleXMLHttpCalls(tenant, headerKey) {
XMLHttpRequest.prototype.orignalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
this.orignalOpen.apply(this, arguments);
this.setRequestHeader(headerKey, tenant);
};
}
function handleAxiosCalls(tenant, headerKey) {
if (! window.axios) return;
window.axios.defaults.headers.common[headerKey] = tenant;
}
@ahmedsayedabdelsalam
Copy link
Author

ahmedsayedabdelsalam commented Aug 16, 2023

add this meta tag to your layout

@if(tenant())
    <meta name="tenant" content="{{ tenant('id') }}">
@endif

import it in bootstrap.js in laravel app

/**
 * Set X-Tenant request header for tenant domains.
 */
const tenantTag = document.head.querySelector('meta[name="tenant"]');
if (tenantTag) {
    import('./utils/set-tenant-header')
        .then(module => module.default(tenantTag.content))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment