Cloudflare Pages Middleware
Cloudflare Pages has it's own concept for middleware functions https://developers.cloudflare.com/pages/functions/middleware/
export async function onRequest(context) {
try {
return await context.next();
} catch (err) {
return new Response(`${err.message}\n${err.stack}`, { status: 500 });
}
}
hono/cloudflare-pages currently provides a handle adapter to use hono with Pages Function, and a serveStatic adapter to handle static assets. It would be great if there was a similar adapter for Pages middleware.
My specific use-case is using HTMLRewriter to rewrite static assets based on the value of a cookie.
// functions/_middleware.ts
import { getCookie } from 'hono/cookie'
import { handleMiddleware } from 'hono/cloudflare-pages'
export const onRequest = handleMiddleware(async (c, next) => {
const myCookie = getCookie(c, 'my_cookie')
const response = await next()
// Alternative API similar to Pages middleware
const response = await c.next()
return new HTMLRewriter()
.on('head', new InjectScriptHandler(myCookie))
.transform(response)
})
Let me know if this is worth adding, I'd be happy to contribute
Where did you import the HTMLRewriter?
I think you can create reference to their website. Since HTMLRewriter was a Cloudflare utility
Adding this to Hono would cause confusion from people who does not use Hono.
Hi @BarryThePenguin
Looks good! I'd like you to work on this.
Regarding next, I think the following is better.
const response = await next()