CF functions middleware + regular function

Hello everyone.
Currently, I have a set of functions that do various things. One of them being logout.js function which just clears cookies and redirects the user somewhere:

export async function onRequest(context) {
	const url = new URL(context.request.url);
	const res = Response.redirect(url.origin);
	res.headers.append('Set-Cookie', `authMethod=;Max-Age=0;`)
	res.headers.append('Set-Cookie', `authToken=;Max-Age=0;`)
	return res;
}

Now, I want to build full serverless service, so I generate all my HTML somehow, but all of the pages should have some dynamic parts. For example, when a user is logged in the user should see logout button instead of login. I used HTMLRewriter for this.
_middleware.js:

export async function onRequest(context) {
	const url = new URL(context.request.url);
	const asset = await env.ASSETS.fetch(url);
	const contentType = asset.headers.get('Content-Type');
	if (contentType.startsWith('text/html')) {
		...
		return new HTMLRewriter()
		.on('login-info', new UserElementHandler(username))
		.transform(asset);
	} else {
		return asset;
	}
}

the problem here is that the function logout is not being run, the request goes to _middleware.js and that’s it. I also tried using context.next() in various places but that doesn’t work.

How can I use HTMLRewriter for all served HTML and route the request to its designated function (for example, logout, which doesn’t return any HTML, it just sets some cookies)?