hono icon indicating copy to clipboard operation
hono copied to clipboard

Cloudflare Pages Middleware

Open BarryThePenguin opened this issue 1 year ago • 2 comments

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

BarryThePenguin avatar Jun 21 '24 13:06 BarryThePenguin

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.

fzn0x avatar Jun 23 '24 09:06 fzn0x

Hi @BarryThePenguin

Looks good! I'd like you to work on this.

Regarding next, I think the following is better.

const response = await next()

yusukebe avatar Jun 23 '24 20:06 yusukebe