NextJS Middleware.ts file not triggered

46 Views Asked by At

I have a NextJS React Project. It has the following file structures: src/app contains all pages. There is no src/app/pages. In my setup, for example, the login page would be called by "/login" where src/app/login/page.tsx is the page being rendered. I added a middleware.ts to src/app/ so it is in the format "src/app/middleware.ts".

"paths": {
     "@/*": ["./src/*"]
    }
 },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]

However the issue is that it is not being triggered. I have attached my tsconfig below:

Any help on this issue would be great

I've tried adding a pages folder in src/app/pages. I've tried changing the tsconfig file as well but not sure if I've done it completely right. I also tried to put middleware.ts at the same level as app but I got the following error

Error: Invalid middleware found.

1

There are 1 best solutions below

0
Beast80K On

Problem :

I added a middleware.ts to src/app/ so it is in the format "src/app/middleware.ts"

Cause :

  • Improper Middlware file location src/app/middleware.ts you placed it inside of app,
  • middleware.ts should be at same level(outside) of app folder,
  • If you have src then inside of src folder.

Solution :

  • middleware.ts should be outside of app.

If you have src then src/middleware.ts :

projectName
├── src
    ├── middleware.ts
    ├── app

If you don't have src then projectName/middleware.ts :

projectName
├── app
├── middleware.ts

Please Read :

If you have any doubts, then please leave a comment (I will update answer if necessary)