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

Maintaining data after page reload in Angular

angular.module('eventTracker', []) .controller('MainCtrl', ['$scope', 'Event', function($scope, Event){ $scope.eventData = {} $scope.onSubmit = function(){ Event.Add($scope.eventData) $scope. ...

Create a dynamic slideshow using a bootstrap carousel in conjunction with the powerful php glob() function

I'm struggling to create a homepage featuring a slider that pulls images dynamically from a subfolder within the Wordpress uploads directory. Here's my code: <div id="" class="carousel slide" data-ride="carousel"> <!-- Wrapper for sl ...

What is the process for generating an API endpoint in Next.js that includes a query string?

I am currently working on setting up an API endpoint in Next.js, specifically the following one: /api/products/[name]?keyword=${anykeyword}. To accomplish this, I understand that I have to create it within the pages/api/products/[name] directory in index ...

Transforming into an input field from a dropdown with Bootstrap select when using AJAX in js.erb

I'm encountering a small issue while updating the view results via AJAX in Ruby on Rails (js.erb). Specifically, when I update/render the form using AJAX, the selectpicker transforms into a simple input and disappears from the view. Any suggestions on ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...

Tag in HTML not being replaced

Within my HTML snippet, I have encountered some <br> tags <div id="reading-project"> <p>The next morning, as soon as the sun was up, they started on their way, and soon saw a beautiful green glow in the sky just before them."That must b ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

The component is expected to return a JSX.Element, however it is failing to return any value

The issue lies with this component: const NavigationItems = (props: {name: string, href: string}[]): JSX.Element => { props.map((item, index) => { return <a href={item.href} key={index}>{item.name}</a> }) }; export default Naviga ...

Breaking up and processing a given string in JavaScript: Splitting and token

When it comes to dealing with this specific JavaScript requirement, the challenge lies in working with a string such as: “ [ condition12 (BRAND) IN 'Beats by Dr. Dre & D\’Silva of type Band’ of type 'IDENTIFIER_STRING’ ] ...

What is the best way to run a function within an if statement without duplicating code if the condition is false?

When working with relay mutation code, I find it necessary to reload the store in order for it to sync with the database. This is because if the text being added is the same as previously added text, the relay store throws an error called flattenChildren.. ...

"Error: Variable becomes undefined due to the implementation of async-await in TypeScript

There has been a persistent issue I've been dealing with for some time now. The problem lies in the fact that vm_res is undefined within the async update_vm_raw_device function despite the function running smoothly. As a result, the value being update ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

The error message "Uncaught TypeError: Unable to retrieve the 'length' property of an undefined object in Titanium" has occurred

Here is the data I am working with: {"todo":[{"todo":"Khaleeq Raza"},{"todo":"Ateeq Raza"}]} This is my current code snippet: var dataArray = []; var client = new XMLHttpRequest(); client.open("GET", "http://192.168.10.109/read_todo_list.php", true); c ...

Javascript function fails to trigger when clicked

<body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-dark"> <h1 class="title">AppifyLife</h1> </ion-header-bar> <ion-content> <center><div class="card" id="life"><h3>20< ...

VS Code lacks autocomplete intellisense for Cypress

I am currently using Cypress version 12.17.1 on VS Code within the Windows 10 operating system. My goal is to write Cypress code in Visual Studio Code, but encountered an issue where the cypress commands that start with cy are not appearing as auto-comple ...