Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cloudflare Pages Middleware #3015

Closed
BarryThePenguin opened this issue Jun 21, 2024 · 2 comments · Fixed by #3028
Closed

Cloudflare Pages Middleware #3015

BarryThePenguin opened this issue Jun 21, 2024 · 2 comments · Fixed by #3028
Labels
enhancement New feature or request.

Comments

@BarryThePenguin
Copy link
Contributor

BarryThePenguin commented Jun 21, 2024

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 BarryThePenguin added the enhancement New feature or request. label Jun 21, 2024
@fzn0x
Copy link
Contributor

fzn0x commented Jun 23, 2024

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.

@yusukebe
Copy link
Member

Hi @BarryThePenguin

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

Regarding next, I think the following is better.

const response = await next()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants