#Pass custom headers to LangGraphHttpAgent (FastAPI)

1 messages · Page 1 of 1 (latest)

cunning quarry
#

How can we pass custom headers (e.g., Authorization header) to a fastAPI server ?
( i have an API GATEWAY to verify the authN and authZ before accessing the server)

harsh groveBOT
#

Hey, if your FastAPI app is sitting behind an API Gateway that needs to check auth, you'll want the gateway to actually see the Authorization header in the HTTP request.
These docs should help you out: Auth overview (covers how CopilotKit handles LangGraph auth for platform vs self-hosted), Runtime configuration (shows how to pass tokens into your agent), and the CopilotKit provider reference (explains the headers prop).
Since your gateway needs to validate the header - use the headers prop in CopilotKit like this:

<CopilotKit 
  headers={{ Authorization: `Bearer ${token}` }}
  runtimeUrl="/api/copilotkit"
>
  <YourApp />
</CopilotKit>

```This actually sends the Authorization header with the HTTP request, so your gateway can see it and do its validation.
cunning quarry
#

thankyou @stark vector 👍

cunning quarry
#

Hi there @stark vector , i tried your solution but it did not work as expected, your solution works for NextJs runtime only (/api/copilotkit) and will not work for external fastAPI server

#

Here is a code snippet for a working implementation, for those who are struggling with similar prblm:

export const POST = async (req: NextRequest) => {
    // <- Must construct the headers within request scope ! 
    const {getAccessTokenRaw} = getKindeServerSession()
    const accessToken = await getAccessTokenRaw();
    // <- e.g., auth header
    const authZ = {
            Authorization: `Bearer ${accessToken}`,
        }


    const runtime = new CopilotRuntime({
        agents: {
            "catalog_consultant": new LangGraphHttpAgent({
                url: "http://localhost:8080/api/v1/agents/agui/catalog_consultant",
                headers: authZ // <-- append the header
            }),
            "product_consultant": new LangGraphHttpAgent({
                url: "http://localhost:8080/api/v1/agents/agui/product_consultant",
                headers: authZ
            }),
            // etc ..
        },
    });
    const {handleRequest} = copilotRuntimeNextJSAppRouterEndpoint({
        runtime,
        serviceAdapter,
        endpoint: "/api/copilotkit",
    });

    return handleRequest(req);
};
#

Here we send the headers directly to the FastAPI server from the POST request scope, i tested it and it worked as expected

harsh groveBOT
#

Thank you for sharing the solution 👍