Skip to content

Add multiple origins setup in middleware when creating monorepo #218

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

Open
jochemvanweelde opened this issue May 3, 2025 · 0 comments · May be fixed by #263
Open

Add multiple origins setup in middleware when creating monorepo #218

jochemvanweelde opened this issue May 3, 2025 · 0 comments · May be fixed by #263

Comments

@jochemvanweelde
Copy link

When creating the following stack: bun create better-t-stack@latest better-t-stack --yes --frontend native next --backend next --runtime node --api orpc --database none --orm none --no-auth --addons biome husky turborepo. (Turbopack with nextjs server, nextjs web and RN expo)

In a monorepo multiple apps consume a single api. The CORS middleware on the server should have support for that.
In this stack next web runs on :3001 and RN web on :8081.

I would like to propose the following change:

in apps/server/.env change CORS env to CORS_ORIGINS=http://localhost:3001,http://localhost:8081
Then in the middleware we can get the origin of the request by doing something like this

import { NextRequest, NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  const originHeader = request.headers.get("origin");
  const res = NextResponse.next();

  const allowedOrigins = process.env.CORS_ORIGINS?.split(",") ?? [];
  if (originHeader && allowedOrigins.includes(originHeader)) {
    res.headers.append("Access-Control-Allow-Origin", originHeader);
  }

  res.headers.append("Access-Control-Allow-Credentials", "true");
  res.headers.append("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
  res.headers.append(
    "Access-Control-Allow-Headers",
    "Content-Type, Authorization"
  );

  return res;
}

export const config = {
  matcher: "/:path*",
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant