Currently, I am in the process of developing a website that incorporates subdomains. Each subdomain is linked to a file-based page using middleware. Take a look at how the subdomains are being mapped to specific pages:
app.com
corresponds to/home
app.com/pricing
corresponds to/home/pricing
subdomain1.app.com/dashboard
corresponds to/_subdomains/subdomain1/dashboard
corresponds tosubdomain2.app.com/dashboard/home
/_subdomains/subdomain2/dashboard/home
Most subdomains like app.com
, subdomain1.app.com
, and subdomain1.app.com/dashboard/
work perfectly fine. However, I am encountering a 404 Not Found error when attempting to access
subdomain1.app.com/dashboard/home
.
This is how my directory structure looks:
pages/
├── _subdomains/
│ └── [subdomain]/
│ ├── dashboard/
│ │ ├── home.tsx
│ │ └── index.tsx
│ └── index.tsx
├── home/
│ └── ...
└── _app.tsx
import { NextRequest, NextResponse } from 'next/server';
export const config = {
// I suspect that this part isn't correctly matching /_subdomains/subdomain/dashboard/home
matcher: ['/', '/([^/.]*)', '/auth/([^/.]*)', '/_subdomains/:path*'],
};
export default async function middleware(req: NextRequest) {
const url = req.nextUrl;
const hostname = req.headers.get('host') || process.env.ROOT_DOMAIN;
if (!hostname) {
throw Error('Middleware -> No hostname');
}
const currentHost = hostname.replace(`.${process.env.ROOT_DOMAIN}`, '');
if (currentHost === process.env.ROOT_DOMAIN) {
url.pathname = `/home${url.pathname}`;
} else {
console.log(`/_subdomains/${currentHost}${url.pathname}`)
url.pathname = `/_subdomains/${currentHost}${url.pathname}`;
}
return NextResponse.rewrite(url);
}
I have a hunch that the issue lies with the matcher that's not functioning as expected, but I'm unsure of the exact reason for it.
The match /_subdomains/:path*
should align with /_subdomains/a/b/c
based on the documentation, however, it doesn't seem to be working correctly in this scenario. There could potentially be another factor causing the problem, but I can't pinpoint it at the moment.