Skip to content

Allow onRequest middleware to add headers that the schema requires #2073

Open
@jnatmorris

Description

@jnatmorris

To my understanding, if one has multiple protected routes, say /auth/*, which are specified in the schema and require an Authorization header, currently it is required to set the header with each request.

const authRequest1 = await client.GET("/auth/sample1", {
	params: {
		header: {
			authorization: `Bearer ${await someAuthFunc()}`
		}
	}
});

const authRequest2 = await client.GET("/auth/sample2", {
	params: {
		header: {
			authorization: `Bearer ${await someAuthFunc()}`
		}
	}
});

While the current implementation of middleware allows for setting a request header, TS still requires an authorization to be set with each individual request. So doing the following becomes not possible.

import createClient, { type Middleware } from "openapi-fetch";
import type { paths } from "./my-openapi-3-schema";

const authMiddleware: Middleware = {
  async onRequest({ request }) {
    request.headers.set("authorization", `Bearer ${await someAuthFunc()}`);
    return request;
  },
};

const client = createClient<paths>({ baseUrl: "https://myapi.dev/v1/" });
client.use(authMiddleware);

// TS errors as no authorization header is added
const authRequest1 = await client.GET("/auth/sample1");
const authRequest2 = await client.GET("/auth/sample2");

While this does not invalidate many of the use cases for middleware, which are great, this use case would be a welcome addition.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or requestopenapi-fetchRelevant to the openapi-fetch libraryopenapi-fetch-codegenRequires codegen for openapi-fetch

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions