I just finished debuggging for several hours over this CORS middleware issue:

XMLHttpRequest at ‘https://xxxxxxxxxxxxxxx.ngrok-free.app/fastAPI_endpoint' from origin ‘http://localhost:5173 or your netlify deployment URL’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Detailed Stack I was using:

  • fastAPI to route backend requests
  • uvicorn to run the server, hosted on default 127.0.0.1:8000
  • axios to send requests from the frontend
  • TypeScript/React with Vite for frontend
  • ngrok (free tier) to reroute a public https URL to the server address

I explored $10 worth of GPT-4 assistance, all relevant StackOverFlow forums, and these close-but-no-cigar Github threads: One, Two.

Solution

What actually worked for me was creating an ngrok.yml file at the root of my backend directory (where the ngrok.exe is).

The contents of the file were:

version: 1
tunnels:
    app:
        addr: 8000
        proto: http
        host_header: rewrite
        bind_tls: true

The important thing is host_header: rewrite.

When set to “rewrite,” ngrok will rewrite the Host header of incoming requests to match the hostname of the tunnel. Without this, there will be a mismatch of the header which is why even if you configure your fastAPI middleware correctly (seen below), you still get those errors. This is necessary when your local server relies on the Host header for processing requests correctly (fastAPI middleware).

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(
    title="Hedilog Beta API",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "http://localhost:5173",    # Your localhost vite project
        "https://xxxxxxxxxxxx.ngrok.io",    # your ngrok URL
        "https://deployment.com",  # your deployment
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

After this is done, run the ngrok instance in your CLI with this command:

ngrok http 8000 --config path/to/ngrok.yml

I hope this helps some poor soul who might be suffering out there.