Search code examples
reactjsnext.jsmiddleware

Function Exported by Next.js middleware.ts not Triggered


Regarding the following code (a StackBlitz version can be found here), why wasn't the function exported by the Next.js middleware.ts file triggered when I accessed https://[domain]/dashboard/profile ?

/app/middleware.ts:

import { NextResponse, NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
   console.log('--> middleware.tsx');
   return NextResponse.redirect(new URL('/home', request.url));
}

/app/dashboard/profile/page.tsx:

export default async function Profile() {
   console.log('--> page.tsx');
   let v = (
      await (
         await fetch(
           'https://webcodingcenter1gkq8ip-biih--3000--810981ba.local-credentialless.webcontainer.io/dashboard'
         )
      ).json()
   ).visits;
  return <h1>{v}</h1>;
}

/app/dashboard/route.tsx:

import { NextResponse } from 'next/server';
var visits = 1;
export async function GET(request: Request) {
   console.log('--> route.tsx');
   visits++;
   return NextResponse.json({ visits });
}

Solution

  • Simply because you are putting the middleware.ts inside the app folder, it has to be either in the root or if you are using a src folder you can place it inside it.

    From Next.js official docs:

    Use the file middleware.ts (or .js) in the root of your project to define Middleware. For example, at the same level as pages or app, or inside src if applicable.

    Check the updated stackblitz snippet