Setting up Next.js Middleware with Page Extensions


Here’s a quick tip for getting middleware working correctly with Next.js if you are setting custom pageExtensions in your next.config.js. I went in circles on this and just could not figure out what was going on so thought I’d share this to provide another avenue to folks discovering the solution.

We have a need for setting pageExtensions in my project so our config looks like this:

/\*_ @type {import('next').NextConfig} _/;
const nextConfig = {
  reactStrictMode: false,
  swcMinify: true,
  pageExtensions: ["page.tsx"],
};

module.exports = nextConfig;

The special middleware.ts (or middleware.js) file is supposed to live as a sibling to your /pages directory. That’s no problem. Add the file there. Here’s super barebones middleware file that we can use to test with.import type { NextRequest } from ‘next/server’;

export function middleware(request: NextRequest) {
  console.log(request);
}

This will simply log the request to the server console. So as soon as we have things set up correctly you should see this log.

The issue is that there is something related to having pageExtensions set that causes the middleware file to be ignored.

The solution is to use the custom page extension that you have set. So in my case once I renamed the middleware file to middleware.page.tsx Next.js picked it up and everything began to work as expected. I’ll say it does feel a little odd to see the .tsx extension there, but it does seem to work. This might be a bug so keep your eyes peeled for a change here in the future if you leverage this solution.