Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HonoJS CORS with cloudflare worker

I'm starting with cloudflare worker and used the recommended routing framework HonoJS. Now the documented way of implementing cors functionallity doesn't work for me on my developement machine (npm run dev). I didn't test it on production, since I need it to work on development environment.

The problem is: The OPTION request gets an 404 returned.

How do I set a global CORS configuration?

My code is currently this:

import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { basicAuth } from 'hono/basic-auth'

import { default as register } from './register.js'

const app = new Hono()
app.use('*', cors())

const user = new Hono()
// also tried: user.use('/*', cors())
user.post('/register', register)

// Register route groups
app.route('/user', user)

export default app

Also tried following cors call:

cors({
    origin: 'http://localhost:5173',
    allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
    allowMethods: ['POST', 'GET', 'OPTIONS'],
    exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
    maxAge: 600,
    credentials: true,
})
like image 225
David Avatar asked Jan 31 '26 04:01

David


1 Answers

I fixed it by adding a wildcard for options.

app.use('*', cors({
    origin: 'http://localhost:5173',
    allowHeaders: ['Content-Type', 'Authorization'],
    allowMethods: ['POST', 'GET', 'OPTIONS'],
    exposeHeaders: ['Content-Length'],
    maxAge: 600,
    credentials: true,
}))

app.options('*', (c) => {
    return c.text('', 204)
})
like image 75
David Avatar answered Feb 03 '26 11:02

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!