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

CORS SEEMS NOT WORKING #3816

Open
moshOntong-IT opened this issue Jan 9, 2025 · 0 comments
Open

CORS SEEMS NOT WORKING #3816

moshOntong-IT opened this issue Jan 9, 2025 · 0 comments
Labels

Comments

@moshOntong-IT
Copy link

What version of Hono are you using?

4.6.16

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

Bun

What steps can reproduce the bug?

For example I have localhost, so in cors origin should be localhost as well. but to test if CORS is work try to replace the localhost into example.com Then try your frontend

What is the expected behavior?

  1. It should throw an error because localhost is not accepted

What do you see instead?

It can proceed to next or can access my backend

Additional information

import { cors } from "hono/cors";
import { createMiddleware } from "hono/factory";
import logger from "../configs/winston-config";
import { ErrorTypeCode } from "../error-type";
import { getCookie } from "hono/cookie";
import { lucia } from "../configs/lucia-config";

if (!Bun.env.APP_DOMAIN) {
  throw new Error("APP_DOMAIN environment variable is not set");
}
const corsForSession = cors({
  origin: "example.com",
  credentials: true,
});

const corsForApiKey = cors({
  origin: "*",
  allowHeaders: ["x-frontida-key"],
});
const corsExtension = createMiddleware(async (c, next) => {
  const origin = c.req.header("origin");
  logger.info(`CORS middleware:  ${c.req.url} with origin of ${origin}`);
  const apiKey = c.req.header("x-emerald-key");
  const sessionCookie = getCookie(c, lucia.sessionCookieName);

  if (apiKey && sessionCookie) {
    logger.error(
      "Both API key and session cookie are present, rejecting request"
    );

    return c.json(
      {
        error: "Using both API key and session cookie is forbidden",
        code: ErrorTypeCode.GeneralConflict,
      },
      400
    );
  }

  if (apiKey) {
    c.set("authorizationType", "api-key");
    logger.info("API key provided, passing request to next middleware");
    return await corsForApiKey(c, next);
  } else {
    c.set("authorizationType", "cookie");

    logger.info(
      "Defaulting to session cookie, passing request to next middleware"
    );
    return await corsForSession(c, next);
  }
});

export default corsExtension;

Be note that I can access my front end using localhost, then to access my backend is localhost/api

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

No branches or pull requests

1 participant