Skip to content

Cors middleware doesn't work with request headers #3951

Closed
@fredrik-sogaard

Description

@fredrik-sogaard

What version of Hono are you using?

4.7.2

What runtime/platform is your app running on? (with version if possible)

Vercel

What steps can reproduce the bug?

  1. Create two NextJS apps: frontend and backend
  2. Run both at two different ports.
  3. Create a simple Hono app with one route.
  4. Add cors middleware.
  5. Create a RPC client and try to fetch the route.
  6. Add any header to the RPC client fetch, and see the request fail when run from the client.

What is the expected behavior?

Cars should work with request headers.

What do you see instead?

Cors fails with:

Access to fetch at 'http://localhost:8000/api/v1/users/me' from origin 'http://localhost:3003' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Additional information

Example code

// lib/honoClient

import { AppType } from 'api/src/api/index' // backend app
import { hc } from 'hono/client'

export function getClient() {
    return hc<AppType>(`http://localhost:8000`, {
      headers: { Authorization: `Bearer some-token-here` }, // does not work
    })

   // return hc<AppType>(`http://localhost:8000`) // Works
  }
}
// components/clientRequest.tsx
import { getClient } from '@/lib/honoClient'
import { useEffect, useState } from 'react'

export default function ClientRequest() {
  const [user, setUser] = useState('')

  const getUser = async () => {
    try {
      const client = getClient()
      const res = await client.api.v1.users.me.$get()
      const user = await res.json()
      // check if the response is ok
      if (!res.ok) {
        throw new Error('Network response was not ok')
      } else {
        setUser(JSON.stringify(user))
      }
    } catch (err) {
      console.error(err)
    }
  }

  useEffect(() => {
    void getUser()
  }, [])

return (
    <pre>{user}</pre>
  )
}

// api/index
import { Hono } from 'hono'
import { cors } from 'hono/cors'

export const app = new Hono()
  .basePath('/api/v1')
  .use('*', cors())
  .route('/users', userRoute)

I've tried many different settings for the core middleware, but nothing seems to work. I've also tried to move and remove the basePath option. Everything works when the fetch is run from a server component.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions