Sami
Sami

Reputation: 195

NextJS Middleware Matcher For Dynamic Routes

I'm building a website with subdomains. Each subdomain is mapped to a file-based page using middleware. Below is an example of how I'm mapping subdomains to pages:

app.com, subdomain1.app.com and subdomain1.app.com/dashboard/ and everything else are working fine, but when I try to access subdomain1.app.com/dashboard/home I'm getting 404 Not Found.

Here's my folder structure:

pages/
├── _subdomains/
│   └── [subdomain]/
│       ├── dashboard/
│       │   ├── home.tsx
│       │   └── index.tsx
│       └── index.tsx
├── home/
│   └── ...
└── _app.tsx
import { NextRequest, NextResponse } from 'next/server';

export const config = {
  // I have a feeling this isn't 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'm fairly certain it's the matcher that isn't working but I don't know why.

Matching /_subdomains/:path* should match /_subdomains/a/b/c according to the docs but it isn't working in this case. Or it could be another issue I'm not sure

Upvotes: 1

Views: 5975

Answers (1)

Sami
Sami

Reputation: 195

Fixed by changing the matcher to

matcher: [
     /*
      * Match all paths except for:
      * 1. /api routes
      * 2. /_next (Next.js internals)
      * 3. /fonts (inside /public)
      * 4. /examples (inside /public)
      * 5. all root files inside /public (e.g. /favicon.ico)
      */
     "/((?!api|_next|fonts|examples|[\\w-]+\\.\\w+).*)",
   ],

Thanks to this

Upvotes: 4

Related Questions