Replies: 44 comments 104 replies
-
This looks great! Does Would it be possible, for example, to add arbitrary data to the context object that can subsequently be accessed in a |
Beta Was this translation helpful? Give feedback.
-
Fascinating! Will it run only before response, or after response as well? For server-side analytics, it doesn't make sense to call some API, before the page has been seen. |
Beta Was this translation helpful? Give feedback.
-
This is brilliant! |
Beta Was this translation helpful? Give feedback.
-
Does this include statically generated pages with |
Beta Was this translation helpful? Give feedback.
-
Given it works for static pages and the no-Node.js API support, it looks like you are intending _middleware to run on an edge function, correct? |
Beta Was this translation helpful? Give feedback.
-
Will it run just on initial page load, or on page transitions with next/router as well? I would like to run certain middleware just on initial page load, and some other on each page load (navigated via next/router). |
Beta Was this translation helpful? Give feedback.
-
I am eagerly awaiting this feature! I'm developing a plugin for A/B testing called next-with-split. https://github.com/aiji42/next-with-split This plugin creates If the middleware is supported natively, it can deliver content more flexibly. |
Beta Was this translation helpful? Give feedback.
-
Would this allow be to track request durations so I can expose these with Prometheus? Currently, I am using a custom express middleware but it's impossible to get the file-based route path which makes metrics have a unnecessary high cardinality |
Beta Was this translation helpful? Give feedback.
-
Are you providing some type of adapter so we can easily use any existing express/connect middleware? |
Beta Was this translation helpful? Give feedback.
-
If, say, I wanted a different middleware stack for my pages vs api routes is there a way to exclude the |
Beta Was this translation helpful? Give feedback.
-
Hope this can handle the following use cases: |
Beta Was this translation helpful? Give feedback.
-
Will it be / is it possible to pass data from middleware to _app.ts? |
Beta Was this translation helpful? Give feedback.
-
Is it possible to skip middleware for particular pages(Not to validate for all the pages)? |
Beta Was this translation helpful? Give feedback.
-
@leerob There are a few use cases for middleware that runs "after" the request has finished:
Currently, is there a way to hook into the // Before middleware
export function middleware(req, ev) {
return new Response('Hello, world!')
}
// After middleware (pseudo code where a middleware has access to response object)
export function middleware(res, ev) {
res.on('finish', () => /* run some code 🚀*/)
} |
Beta Was this translation helpful? Give feedback.
-
Is something like _middleware on the works for api routes? I would like to define just one file with middleware instead of having to use next-connect on each route. |
Beta Was this translation helpful? Give feedback.
-
I skimmed through the thread, but couldn't really find anything with regards to local development testing. It seems that I often have to deploy our application to see problems that arise from the limited API on the edge runtime. Simply put, how does one go about developing/testing Thanks in advance. |
Beta Was this translation helpful? Give feedback.
-
This might be on the silly side, but is there any formal difference, between: export const middleware = (req: NextRequest) => {
return NextResponse.next();
}; and export const middleware = (req: NextRequest) => {
return undefined;
}; I thought that not calling next might not trigger downstream middleware, but that's not the case. I ask this in the context of having some logic in the middleware that concludes that nothing ought to be done. It seems that our code base took the EditIf you care about how we ended up with // we had in _middleware
if(condition) return resolveCondition() In some other file: // lib/helper.ts
const resolveCondition = () => {
/* do some other stuff */
return undefined;
} Inside helper one cannot import from
So the developer tested with returning
|
Beta Was this translation helpful? Give feedback.
-
@leerob According to the docs the middleware will not have access to the crypto package. |
Beta Was this translation helpful? Give feedback.
-
Anyone know why console.trace was not bound here? |
Beta Was this translation helpful? Give feedback.
-
Also, does anyone know if there's a way to access the ORIGINAL req from a middleware? When I'm using Vercel, the locale detection middleware is kicking in before mine, and I can't access the url as requested by the user, it has already be re-written. This makes it impossible to detect if you're about to create an infinite redirect since you don't know what the original url was. |
Beta Was this translation helpful? Give feedback.
-
Would there be Node.js APIs support any time soon?I wanted to store every single access log to ElasticSearch (including HTTP API request, static files, pages whatever). Then I found this middleware API and I sounds like a thing I was looking for. But in a couple of hours I felt disappointed because I just figured out it doesn't support a very popular logging library, winston. "You may find another library!" won't help it. Because in our company, we do manage kind of a logging platform called 'NELO' (which is basically a wrapper of ES) on our own and that NELO team offers a SDK which is also kind of a wrapper of, of course, winston. Maybe it's just me but when I first heard about 'Middleware API' it felt so much like a server-side stuff. And the fact that server-side feature doesn't support Node.js APIs sound a bit ironic to me. |
Beta Was this translation helpful? Give feedback.
-
Seems like the recent PRs (#36772 & #36835) reverse some points that were part of the original RFC:
Could the RFC be updated to reflect the current state of the API design, please? cc @leerob |
Beta Was this translation helpful? Give feedback.
-
Hey everyone! Appreciate all of the feedback here on this RFC as folks have been using Middleware while it's in beta. We're reviewing your feedback and will be incorporating it into the next version of Middleware. I'll share more on this soon with details on how to upgrade and the changes we're making to better support y'all. Thank you! |
Beta Was this translation helpful? Give feedback.
-
The docs don't mention one thing about edge functions: if you're using
|
Beta Was this translation helpful? Give feedback.
-
Using middleware for on-demand revalidation/ISRThe following was already asked in this discussion, adding it here for visibility. Describe the feature you'd like to requestI'm using middlewares to protect sites from unauthenticated access. Unfortunately the new on-demand revalidation and its requests are also intercepted by the middleware. In my case, unauthenticated users are redirected to the sign in page. Here's part of the middleware for reference: // _middleware.ts (in root)
...
if (isSignedIn) {
// user is signed in, go on
return NextResponse.next();
} else {
const urlNew = req.nextUrl.clone();
urlNew.pathname = ROUTES.SIGN_IN;
return NextResponse.redirect(urlNew);
} I obviously don't want to do this redirection for the revalidation requests. Right now, I circumvent this by looking at the header of the middleware request: const isRevalidationRequest = !!req.headers.get("x-prerender-revalidate"); Requests coming from on-demand revalidation ( Is there a better way? Describe the solution you'd likePossible solutions I thought about:
|
Beta Was this translation helpful? Give feedback.
-
In preparation for Middleware stability, we just merged an upgrade guide with the latest API changes. You can try out these changes on the latest npm i -g next@canary |
Beta Was this translation helpful? Give feedback.
-
Hey there! Use case & structure:I'd like to use a middleware to redirect users to Problems & Branches:Too Many RequestsThe middleware code bellow (quite similar to examples) results in redirect loops that are canceled by the browser, since no token is ever set on redirect to the export function middleware(req: NextRequest) {
const token = getAuthToken(req.cookies);
console.log(
`hasToken: ${token ? true : false} | pathName: ${req.nextUrl.pathname}`
);
if (token) {
return NextResponse.next();
} else {
console.log("REDIRECT");
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("from", req.nextUrl.pathname);
return NextResponse.redirect(loginUrl);
}
} _next Path RedirectsI decided to add a condition to allow any access to if (token || req.nextUrl.pathname.match(/login/)) {
return NextResponse.next();
} But that led to issues on requests for Browser Result: "Blank page" Enable Access to _nextAfter that I decided to allow access to all routes that had Am I correct on this approach and assumptions? |
Beta Was this translation helpful? Give feedback.
-
The Middleware API is now stable with Next.js 12.2 🎉 |
Beta Was this translation helpful? Give feedback.
-
@leerob in the above proposal you were mentioning: Users can define Middleware by providing _middleware at any level in the file tree under pages/. right now, the docs say differently https://nextjs.org/docs/app/building-your-application/routing/middleware#convention (just one in the root). That’s why I opened a discussion #69866 . Would you still consider file-system based nesting of middlewares? I’m asking it for all the great file conventions like route groups, dynamic routes, parallel routes and intercepting routes etc. These are at least more difficult to fully utilise in middleware right now, and maybe even impossible? even in the era of server components I would still welcome this, as a request from any server component could still be proxied through files-system based nested (API) middleware functions. |
Beta Was this translation helpful? Give feedback.
-
Goals
Non-Goals
req
andres
).Background
When developers spin up their own solutions using servers, they can influence the request lifecycle with as much middleware as they need (e.g.: by using
app.use()
in Express.js. Currently, Next.js users are constrained by:headers
,rewrites
,redirects
, etc.) which support many scenarios, but don't work for advanced use-cases.Proposal
We propose to introduce a native capability in Next.js to define Middleware, allowing for complete flexibility of the upstream request as well as the response. Middleware would have the ability to add headers to the next request, as well as to the response, and more.
Middleware could be used for anything that shares logic for a set of pages: authentication, bot protection, redirects, handling unsupported browsers, server-side analytics, logging, etc.
To use Middleware with Next.js, you would export a function
middleware
inside a filepages/_middleware.js
2:For example, you could implement basic authentication as follows:
Or more easily support A/B testing:
Users can define Middleware by providing
_middleware
at any level in the file tree underpages/
. For example, if you had a nested Middleware inside/dashboard
, the order of execution would be as follows:pages/_middleware.js
would run first, on every requestpages/dashboard/_middleware.js
would run second, only for pages under/dashboard
Footnotes
Since Middleware could run for each request, including static pages, we want to ensure it will stay fast over time. This requires limiting the runtime inside Middleware to and not supporting the entirety of the Node.js. You would still be able to use ES Modules that did not rely on Node.js APIs, as well as Web Standard APIs. ↩
In the future, we'd like to expose a way to use the same runtime as Middleware for
getStaticProps
,getStaticPaths
,getServerSideProps
, and API Routes. ↩Beta Was this translation helpful? Give feedback.
All reactions