Where Should the Next.js "middleware" File Be Added in the Project Directory?

You should put your Next.js middleware.js (or .ts) file in the root of your project. This means that it should be at the same level as your "app" or "pages" folder:

src/
..└── app/
....└── ...
..└── middleware.js

There are several ways in which you can verify if the contents of the middleware.js file are being read. One such way is by simply adding a console.log() in the file like so:

// middleware.js
export function middleware() {
    console.log('output from middleware.js');
}

You can then check the server logs to see if the output is there.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.