CORS Issue When Accessing Express Server from Published Client Using Cloudflare DNS

I have an Express server and a client application under the example.com domain. The server is accessible via server.example.com, and the client via app.example.com.

Issue:

When trying to access the server from the published client (https://app.example.com), I get the following CORS error:

Access to XMLHttpRequest at 'https://server.example.com/users?_id=TsJYVYrudlOB0c6k0A3qosisLId2' from origin 'https://app.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What Works:
Accessing the server from a local client (running on localhost) works without any issues.
Direct requests to the server using curl return the expected response with the correct CORS headers:

*   Trying 34.32.135.56:443...
* Connected to server.example.com (34.32.135.56) port 443
* schannel: disabled automatic use of client certificate
* ALPN: curl offers http/1.1
* schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
* Closing connection
* schannel: shutting down SSL/TLS connection with server.example.com port 443
curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.

Setup:

Express Server Configuration:

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import http from 'http';

const app = express();
const server = http.createServer(app);

const corsOptions = {
  origin: [
    "http://localhost:5173",
    "http://localhost:5174",
    "http://localhost:5175",
    "https://example.com",
    "https://www.example.com",
    "https://app.example.com",
  ],
  credentials: true,
  allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept"],
  methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
};

app.use(cors(corsOptions));
app.use(express.json());

// Add detailed logging to ensure CORS middleware is applied
app.use((req: Request, res: Response, next: NextFunction) => {
  console.log('Request received:', req.method, req.url);
  console.log('Origin:', req.headers.origin);
  next();
});

app.use((req: Request, res: Response, next: NextFunction) => {
  console.log('CORS headers after CORS middleware:', res.get('Access-Control-Allow-Origin'));
  next();
});

// Example route to test CORS
app.get('/users', (req: Request, res: Response) => {
  res.json({ message: 'CORS is working!' });
});

// Error handling middleware
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.error('An error occurred:', err);
  res.status(500).json({ error: 'Internal Server Error' });
});

// Server listening setup
const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(
    `*********************************************************************** SERVER IS RUNNING ON PORT ${PORT} ***********************************************************************`
  );
});

Client Code:

const baseUserPath = `${import.meta.env.VITE_PUBLIC_SERVER_BASE_URL}/users`;

useEffect(() => {
  if (!auth) return;
  const authStateListener = onAuthStateChanged(auth, (newAuthUserState) => {
    if (newAuthUserState) {
      setAuthUser(newAuthUserState);
      (async () => {
        try {
          const response = await axios.get(baseUserPath, {
            params: {
              _id: newAuthUserState.uid,
            },
            withCredentials: true, // Tried both with and without withCredentials
          });

          setUser(response.data);
        } catch (err: unknown) {
          if (err instanceof Error) {
            throw new Error(err.message);
          }
          throw err;
        } finally {
          setLoadingInitial(false);
        }
      })();
    } else {
      setAuthUser(undefined);
      setUser(undefined);
      setLoadingInitial(false);
    }
  });

  return authStateListener;
}, [auth]);

Steps Taken:

  • Disabled Cloudflare Proxy: Disabled Cloudflare’s proxy for both server.example.com and app.example.com to rule out any proxy-related issues. It has been over 72 hours since the change, so DNS propagation should not be an issue.

  • Verified CORS Configuration: Ensured the CORS middleware is correctly set up in the Express server before any routes.

  • Testing with cURL: Direct access using curl -vk “https://server.example.com/users?_id=TsJYVYrudlOB0c6k0A3qosisLId2” results in SSL errors related to certificate revocation.
    Local Access Works: When accessing the server from a local client running on localhost, the requests are successful, and CORS headers are correctly set.

  • Checked Environment Variables: Verified that the environment variables are correctly set.

  • SSL Certificate Check: Verified that the SSL certificate is valid and trusted by all major web browsers.

** Hosting on Railway: The server is hosted on Railway.

** No Logs When Accessed from Published Client: When trying to access the server from the published client and getting denied, I don’t even see any logs, including error logs.

Request for Help:

I’m looking for insights on why CORS issues persist only when accessing the server from the published client (app.example.com). Any suggestions on what might be causing this issue or further steps to diagnose and resolve it would be greatly appreciated.

Thank you!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật