Repository navigation
How to stop Page Function middleware being called on everything? #2832
Replies: 1 comment
|
The confusing part here is that _routes.json controls something different from what you'd expect. It decides which requests reach Functions and which get served directly as static assets. It can't scope middleware. Middleware in functions/_middleware.ts runs for every request that reaches the Functions runtime, full stop. For your case there are two ways to go. First, move the middleware into a subfolder. Middleware in functions/dashboard/_middleware.ts only runs for routes under /dashboard, so the session check for the dashboard can live there on its own. Second, if you'd rather keep one global middleware, guard it by pathname inside the middleware. Asset requests are easy to spot: the path has a file extension, or it starts with src, node_modules, or a Vite prefix. Pass those straight through with context.next() and leave them alone. export const onRequest = async (context) => {
const pathname = new URL(context.request.url).pathname
if (pathname.startsWith('/dashboard')) {
// check the session cookie here, redirect if not logged in
}
const response = await context.next()
if (!pathname.includes('.')) {
// this is a pushState route, not a file asset, modify the HTML here
}
return response
}About dev: when you run pages dev with a proxy, every request to the Vite dev server goes through Wrangler first, which is why the middleware log shows all those asset requests. In production, once deployed, _routes.json cuts the asset requests off before they ever reach Functions. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
The documentation says that I can place a
_routes.jsonindistto include or exclude files but this seems to have no effect.functions/_middleware.tsI've tried many combos but given a
_routes.jsonlike this:{ "version": 1, "include": ["/favicon.png"], "exclude": [] }The middleware is still called on everything, e.g:
What I would like to do is have a
_middleware.tswhich does two things:On certain routes like
/dashboardcheck a session cookie and redirect if not authorizedOn every route that is not a real asset i.e. a html5 pushState route e.g.
/dashboard, modify the respondingindex.htmloutputAny help appreciated
P.S. I start dev like this:
All reactions