'Next Js: Middleware is ignored for a directory with re-writes

I have a file system like this

Pages
  secure/
    _middleware.ts
    protectedResource.tsx
  _app.tsx
  _document.tsx
  index.tsx

I have next configured like this

module.exports = {
  ...
  async rewrites() {
    return [
      {
        source: '/protectedResource',
        destination: '/secure/protectedResource'
      }
    ]
  }
}

The rewrite works correctly, when accessing http://localhost:3000/protectedResource the user sees the correct route. The middleware from the 'secure' directory, however, is not invoked during the request pipeline. Aside from moving the middleware to the pages directory, how can I resolve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source