Middleware Byepass
The Next.js Middleware
Next.js middleware is a powerful feature that allows developers to run code before a request is completed. As the official Next.js documentation states: "Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly."The middleware functionality in Next.js has numerous use cases, but the most critical ones include:
Path rewriting - Dynamically changing the requested path before it reaches the application logic
Server-side redirects - Redirecting users based on certain conditions
Adding response headers - Including security headers like Content Security Policy (CSP)
Authentication and Authorization - Ensuring user identity and checking session cookies before granting access to specific pages or API routes
common implementation pattern is using middleware for authorization, which involves protecting certain paths based on specific conditions. For example, when a user attempts to access a protected route like
/dashboard/admin, the middleware intercepts the request, checks if the user's session cookies are valid and if they have the necessary permissions. If the conditions are met, the middleware forwards the request; otherwise, it redirects the user to a login page.
For versions prior to 12.2:
In these versions, middleware files had to be named _middleware.ts and placed inside the pages folder. The value of middlewareInfo.name was composed of the directory name and the file name:
x-middleware-subrequest: pages/_middlewareFor nested routes, there could be multiple middleware files at different levels, resulting in multiple possible values for the header:
x-middleware-subrequest: pages/dashboard/_middlewareor
x-middleware-subrequest: pages/dashboard/panel/_middlewareFor versions 12.2 and later:
Starting with version 12.2, Next.js changed the middleware conventions. The file should be named middleware.ts (without the underscore) and should no longer be located in the pages folder. For these versions, the payload is simpler:
x-middleware-subrequest: middlewareAdditionally, Next.js allows for an alternative project structure with a /src directory. In such cases, the payload would be:
For versions 13.2.0 and later:
For versions 13.2.0 and above, Next.js introduced a maximum recursion depth for middleware execution. This was implemented to prevent infinite loops but doesn't affect the vulnerability. The exploitation remains the same, as the header check occurs before any recursion depth checks.
Alternatively, for projects using a /src directory structure:
request will look something like that
Last updated