David
David

Reputation: 388

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,
})

Upvotes: 2

Views: 3336

Answers (1)

David
David

Reputation: 388

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)
})

Upvotes: 8

Related Questions