Dynamic Route Matching in NextJS Middleware

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
  • subdomain2.app.com/dashboard/home
    corresponds to
    /_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.

Answer №1

Resolved by updating the matcher configuration to

matcher: [
     /*
      * Matching 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+).*)",
   ],

Credit goes to this

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Objects cannot be used as constructors

An Azure Function using JavaScript HTTP Trigger posts activity in a Slack online community for customers. It has been functioning successfully for many years, but after upgrading from version ~2 to ~4, it started throwing an error stating Entities is not ...

unable to render the JavaScript code

Utilizing JavaScript post an ajax request to showcase the data in a div using new JS content. The example code is provided below: //ajax call from a.jsp var goUrl = "/testMethod/getTestMethod; var httpRequest=null; var refreshCont ...

What is the solution for breaking a querySnapshot in Firestore?

Is there a way to exit a querysnapshot loop prematurely? I attempted using a for loop, but I keep encountering the following error message. How can this error be resolved or is there an alternative method to break out of a snapshot loop? code return ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

What's the best way to retrieve the dates for the current week using JavaScript?

Could anyone help me find a way to retrieve the first and last dates of the current week? For example, for this week, it would be from September 4th to September 10th. I encountered an issue at the end of the month when dates overlap two months (such as t ...

Regular Expression designed specifically for detecting alternative clicks

When using ngpattern for validation, I have encountered an issue where my error message is displaying for a different reason than intended. The error message should only show if the field is empty or contains only special characters. <textarea name="ti ...

What is the best way to retrieve the ID of the list item that has been clicked during a button event?

How can I use jQuery to get the ID of a selected list item when clicking a button in my HTML code? <ul id="nav"> <li><a href="#" rel="css/default.css" id="default" > <div class="r1"></div> </a>< ...

Utilizing JSON and AJAX for data parsing

I have a PHP page that contains the following code: <?php $library= '{"closets":[ {"id":"001","theme":"literature","shelves": { ...

Establishing data using Vue.js

Apologies for my beginner question, but I have been struggling with a basic issue since yesterday and can't seem to find the solution. I am trying to populate my logs variable with a JSON object and display it in an array. Below is my HTML code : & ...

Invalid parameter or query values detected in the next.js server-side rendering context

Take a look at my directory structure in next.js for handling dynamic routes. https://i.sstatic.net/1Dhpj.png In my product page Server Side (SSR), I utilize params in this manner: https://i.sstatic.net/Hb25y.png While most of the time I am able to retr ...

Ways to transfer property values between two instances of a component

Two datepicker components are present, one for "From" date and another for "To" date. If the "To" date is empty, I want to automatically update it with the value from the "From" date. I have considered using 'emit' on the value but I am unsure ...

Modifying various states within React using the useState() hook

Curiosity strikes me - what actually happens when I modify more than one state in a handler function? Will they be updated simultaneously, or will the changes occur sequentially? const [x, setX] = useState(0) const [y, setY] = useState(0) const handlerFu ...

Issue with back button functionality when loading page with history.pushState in JavaScript

My current issue involves loading a page via ajax using history.pushState. The page loads successfully, but the back button does not work as expected. I have included my code below for reference: function processAjaxData(response, urlPath){ document.wr ...

Is there a way to incorporate the ::after or ::before pseudo-elements into an image tag?

While working on my project, I attempted to incorporate the ::after tag (I had used ::before as well) for an image within an img tag. However, I am facing difficulties as it doesn't seem to be working. Any advice or guidance would be greatly appreciat ...

AJAX is designed to only modify one specific Django model instance at a time

My Django project displays a list of "issue" objects, each with a boolean field called "fixed". I am looking to implement a feature where users can press a button that will modify the "fixed" status using Ajax. However, currently, the button only changes o ...

Using JavaScript's FOR loop in combination with AJAX

I'm encountering an issue with using AJAX and a FOR loop. Within my PHP file, there are several if statements that return different prices based on a number range (1-9). For example: 1 -> echo "15.20"; 2 -> echo "11.10"; 3 -> echo "13.65"; ...

Chai spy does not recognize sinon stubbed functions when verifying function calls

I am working with two asynchronous functions that return bluebird promises: Async1: function() { return new Promise(function(resolve, reject) { execute(query) .then(function(resp) { resolve(resp); }) .catch(function(err) { ...

Retrieving the text content from a JSON key

I have the following JSON data saved in a jQuery variable called "jsondata": var jsondata = { "Name": { "Jaken": {}, "Test": {}, "Hello": {} }, "Date": { "Today": {}, "Tomorrow": {}, "Wednesday": {} }, "Description": { ...

Testing a Mocha import for a class from an unexported namespace

I'm in the process of creating unit tests for my Typescript application using the Mocha test framework. Within my web app, I have an internal module (A) that contains a class B. namespace A { export class B { constructor() { } ...