opnform/client/middleware/custom-domain.global.js

43 lines
1.2 KiB
JavaScript
Raw Normal View History

2024-01-12 14:43:28 +00:00
import {customDomainUsed, getDomain, getHost} from "~/lib/utils.js";
2023-12-16 18:21:03 +00:00
2024-01-12 14:43:28 +00:00
/**
* Added by Caddy when proxying to the app
* @type {string}
*/
const customDomainHeaderName = 'CUSTOM_DOMAIN_HEADER'
/**
* List of routes that can be used with a custom domain
* @type {string[]}
*/
const customDomainAllowedRoutes = ['forms-slug']
function redirectToMainDomain() {
return navigateTo(useRuntimeConfig().public.appUrl + '?utm_source=failed_custom_domain_redirect', { redirectCode: 301, external: true })
2023-12-16 18:21:03 +00:00
}
export default defineNuxtRouteMiddleware((to, from) => {
2024-01-12 14:43:28 +00:00
if (process.client) return
const config = useRuntimeConfig()
if (!customDomainUsed()) return
const customDomainHeaderValue = useRequestHeaders()[customDomainHeaderName]
if (!customDomainHeaderValue || customDomainHeaderValue !== getDomain(getHost())) {
// If custom domain header doesn't match, redirect
return redirectToMainDomain()
}
if (!config.public.customDomainsEnabled) {
// If custom domain not allowed, redirect
return redirectToMainDomain()
}
if (!customDomainAllowedRoutes.includes(to.name)) {
// Custom domain only allowed for form url
return redirectToMainDomain()
2023-12-16 18:21:03 +00:00
}
})