0

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 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

1 Comment

So this is the best explanation I have seen - nextjs is very picky and very specific about the file location. For people building nextJS apps with app router there are basically 3 levels: The root directory or the project (same level is tsconfig.json, next.config.json etc, inside the src folder, and inside the src/app folder). The middleware needs to be on the middle level, if you are using the src folder. The mistake I was making was adding at the root level, which is only applicable whtn you are NOT using a src folder. Thanks to you sir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.