N
Nuxt2w ago
vrijraj

Customize Routing Rule for Main domain and Subdomain(wildcard)

I have created a file app/router.options.ts for the subdomain
import type { RouterConfig } from "@nuxt/schema";
import { useRuntimeConfig } from "#app";
import { useRequestHeaders } from "nuxt/app";

function getSubdomain(host: string) {
const h = host?.split(':')[0].toLowerCase();
const parts = h.split('.');
return parts.length > 2 ? parts[0] : null;
}

function isSubdomainRequest(): boolean {
if (process.server) {
const headers = useRequestHeaders(['host', 'x-forwarded-host']);
const host = headers['x-forwarded-host'] || headers.host || '';
const sub = getSubdomain(host);
return sub && !['www', 'stage'].includes(sub);
}
if (process.client) {
const sub = getSubdomain(location.hostname);
return sub && !['www', 'stage'].includes(sub);
}
return false;
}

function transformRoutes(routes: any[], isSub: boolean, shared: string[]) {
const isSubRoute = (r: any) => r.path.startsWith("/subdomain");
const isShared = (r: any) => shared.some(p => r.path === p || r.path.startsWith(p + "/"));

if (isSub) {
const sharedRoutes = routes.filter(isShared);
const subRoutes = routes.filter(isSubRoute).map(r => ({
...r,
path: r.path.replace("/subdomain", ""),
name: r.name?.replace("subdomain-", "") || "index",
}));
return [...sharedRoutes, ...subRoutes];
}
return routes.filter(r => !isSubRoute(r));
}

export default <RouterConfig>{
routes: (_routes) => {
const { ssrContext } = useNuxtApp();
const config = useRuntimeConfig();
const isSub = isSubdomainRequest();
return transformRoutes(_routes, isSub, ["/about"]);
},
};
import type { RouterConfig } from "@nuxt/schema";
import { useRuntimeConfig } from "#app";
import { useRequestHeaders } from "nuxt/app";

function getSubdomain(host: string) {
const h = host?.split(':')[0].toLowerCase();
const parts = h.split('.');
return parts.length > 2 ? parts[0] : null;
}

function isSubdomainRequest(): boolean {
if (process.server) {
const headers = useRequestHeaders(['host', 'x-forwarded-host']);
const host = headers['x-forwarded-host'] || headers.host || '';
const sub = getSubdomain(host);
return sub && !['www', 'stage'].includes(sub);
}
if (process.client) {
const sub = getSubdomain(location.hostname);
return sub && !['www', 'stage'].includes(sub);
}
return false;
}

function transformRoutes(routes: any[], isSub: boolean, shared: string[]) {
const isSubRoute = (r: any) => r.path.startsWith("/subdomain");
const isShared = (r: any) => shared.some(p => r.path === p || r.path.startsWith(p + "/"));

if (isSub) {
const sharedRoutes = routes.filter(isShared);
const subRoutes = routes.filter(isSubRoute).map(r => ({
...r,
path: r.path.replace("/subdomain", ""),
name: r.name?.replace("subdomain-", "") || "index",
}));
return [...sharedRoutes, ...subRoutes];
}
return routes.filter(r => !isSubRoute(r));
}

export default <RouterConfig>{
routes: (_routes) => {
const { ssrContext } = useNuxtApp();
const config = useRuntimeConfig();
const isSub = isSubdomainRequest();
return transformRoutes(_routes, isSub, ["/about"]);
},
};
Project Structure
pages/
- index.vue // maindomain
- about.vue // maindomain
- subdomain //subdomain folder
- index.vue
pages/
- index.vue // maindomain
- about.vue // maindomain
- subdomain //subdomain folder
- index.vue
In nuxt config
routeRules: {
"/": { ssr: false },
"/about": { prerender: true },
"/**": { ssr: true } // transformed subdomain routes
}
routeRules: {
"/": { ssr: false },
"/about": { prerender: true },
"/**": { ssr: true } // transformed subdomain routes
}
Above, how to customize the route rules for a subdomain
3 Replies
kapa.ai
kapa.ai2w ago
Hi @vrijraj. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To customize route rules for subdomains (including wildcards) in Nuxt, you should use the routeRules feature in your nuxt.config. However, Nuxt’s routeRules are matched against the route path, not the domain or subdomain. This means you cannot directly specify a route rule for a subdomain (like *.example.com) using only the built-in routeRules configuration. Route rules are designed to match URL paths (e.g., /about, /subdomain/**), not hostnames or subdomains [routeRules API]. Key points from the knowledge sources: - routeRules are global options applied to matching server routes, and they match by path, not by domain or subdomain [routeRules API]. - If you need to apply different logic based on the subdomain, you must handle this at runtime (e.g., in middleware, server routes, or custom router logic), not via routeRules in nuxt.config. - Your approach of customizing routes in app/router.options.ts is valid for changing which routes are available based on the subdomain, but it does not affect routeRules, which are still path-based [Custom Routing]. What you can do: - You can continue to use your custom router logic in app/router.options.ts to serve different routes for subdomains. - For routeRules, you can only target the path (e.g., /subdomain/**), not the subdomain itself. - If you need to apply SSR/prerender/caching rules based on the subdomain, you would need to implement this logic in server middleware or in your API/server routes, where you have access to the request headers and can inspect the host. Example:
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { ssr: false },
'/about': { prerender: true },
'/subdomain/**': { ssr: true }, // This matches the path, not the subdomain
'/**': { ssr: true }
}
})
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { ssr: false },
'/about': { prerender: true },
'/subdomain/**': { ssr: true }, // This matches the path, not the subdomain
'/**': { ssr: true }
}
})
This will apply SSR to all /subdomain/** paths, regardless of the domain or subdomain. If you need true subdomain-based rules: You must implement custom logic in server middleware or API routes, where you can check the Host header and apply your own logic accordingly. Nuxt’s routeRules do not support host-based matching as of the current documentation [routeRules API]. Summary:
You cannot directly customize routeRules for subdomains using nuxt.config. Route rules only match paths. For subdomain-specific behavior, use custom server middleware or logic in your router options to inspect the host and apply the desired behavior [Custom Routing]. If you need more advanced host-based routing, consider using a reverse proxy (like Nginx) in front of your Nuxt app to route requests to different Nuxt instances or endpoints based on the subdomain. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2w ago
<@600276141252673536> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
vrijraj
vrijrajOP2w ago
not working

Did you find this page helpful?