Skip to content

[typescript-axios] Add User-Agent Header to Default Axios #20067

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

Merged
merged 13 commits into from
Dec 17, 2024

Conversation

ckoegel
Copy link
Contributor

@ckoegel ckoegel commented Nov 8, 2024

This PR adds a User-Agent header to the default axios instance created in base.ts. This conforms with other generators that set the user agent header based on the package version, i.e OpenAPI-Generator/1.0.0/typescript-axios

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package 
    ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.x.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@TiFu (2017/07) @taxpon (2017/07) @sebastianhaas (2017/07) @kenisteward (2017/07) @Vrolijkx (2017/09) @macjohnny (2018/01) @topce (2018/10) @akehir (2019/07) @petejohansonxo (2019/11) @amakhrov (2020/02) @davidgamero (2022/03) @mkusaka (2022/04) @joscha (2024/10)

@ckoegel
Copy link
Contributor Author

ckoegel commented Nov 8, 2024

updated to make the mustache logic contained in one line
I couldn't think of a simple way to test this change, let me know if/what to do about that

@joscha
Copy link
Contributor

joscha commented Nov 8, 2024

updated to make the mustache logic contained in one line
I couldn't think of a simple way to test this change, let me know if/what to do about that

You can generate a new fixture where you pass the version in additionalProperties - have a look at the yamls we have in the repo already, some of them set other vars as well. You can change an existing one or add a new one.

@@ -10,6 +10,8 @@ import globalAxios from 'axios';

export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, "");

globalAxios.defaults.headers.common['User-Agent'] = "OpenAPI-Generator{{#npmVersion}}/{{npmVersion}}{{/npmVersion}}/typescript-axios";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't we rather set this inside the API, so it doesn't change other axios calls outside of the generated code?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think so. It also makes it impossible to provide an axios instance with a specific behavior as each time this code runs it will revert the default?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this globalAxios instance is used as the default when a new api instance is created. It shouldn't affect anything outside of this code afaik. In the tests (specifically here ), we create a custom axios instance and pass it into the test suite. This axios instance contains the default axios/1.6.1 User-Agent header and not the generated one. Only in the tests where an instance is not passed in does the OpenAPI-Generator/1.0.0/typescript-axios header appear.

I can try to add some asserts inside an interceptor to guarantee the User-Agent header remains the default axios header when using the custom instance in these tests, but like I said earlier in the thread I couldn't think of a way to intercept the requests coming from the default instance in BaseAPI and assert those.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, it would affect other code outside of this package that does import globalAxios from 'axios';, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, it would affect other code outside of this package that does import globalAxios from 'axios';, right?

Normally yes, I would expect this to behave like that, but in this case it doesn't seem to work that way. In the PetApi tests, I'm able to see the behavior you mention, where any import of the default axios export is the same instance of axios, but the instance that exists in the test file is not the same as the one created in base.ts. I honestly don't know how all of this works well enough to know why, so if you can explain more I'd appreciate it. My best guesses are:

  1. Since the globalAxios instance is created inside a node_module when the package is imported, maybe it creates a new instance when axios is imported in another module, in this case the test module?
  2. The built base.js file that comes from base.ts uses a require instead of import, and then references the .default of the required var (snippet below), perhaps this is why?
var axios_1 = require("axios");
exports.BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, "");
axios_1.default.defaults.headers.common['User-Agent'] = "OpenAPI-Generator/1.0.0/typescript-axios";

I also did some digging in the axios source, and it seems like at some points they do some omitting of the defaults.headers (here) I doubt this is related though.

Here's a snippet of the modified PetApi.ts test file where I verify that the two imported axios' in this file are in fact the same instance of axios, but the globalAxios does not have the assigned header that comes from base.ts.

import { expect } from "chai";
import { PetApi, Pet, PetStatusEnum, Category } from "@openapitools/typescript-axios-petstore";
import axios, {AxiosInstance, AxiosResponse} from "axios";
import globalAxios from "axios";

describe("PetApi", () => {
  function runSuite(description: string, requestOptions?: any, customAxiosInstance?: AxiosInstance): void {
    describe(description, () => {
      let api: PetApi;
      const fixture: Pet = createTestFixture();

      beforeEach(() => {
        api = new PetApi(undefined, undefined, customAxiosInstance);
      });

      it("should add and delete Pet", () => {
        return api.addPet(fixture, requestOptions).then(() => {});
      });
    });
  }

  globalAxios.interceptors.response.use(res => {
    console.log('globalAxios', res.request._header);
    return res;
  }, error => Promise.reject(error));

  console.log("same instance? ", axios === globalAxios);
  console.log("globalAxios headers: ", globalAxios.defaults.headers.common);

  runSuite("without custom axios instance");

  runSuite("with custom axios instance",{}, globalAxios);

});

function createTestFixture(ts = Date.now()) {
  const category: Category = {
    id: ts,
    name: `category${ts}`
  };

  const pet: Pet = {
    id: ts,
    name: `pet${ts}`,
    category: category,
    photoUrls: ["http://foo.bar.com/1", "http://foo.bar.com/2"],
    status: PetStatusEnum.Available,
    tags: []
  };

  return pet;
}

Console Output:

> [email protected] test
> mocha test/*.ts --require ts-node/register --timeout 10000

same instance?  true
globalAxios headers:  {
  Accept: 'application/json, text/plain, */*',
  'Content-Type': undefined
}


  PetApi
    without custom axios instance
      ✓ should add and delete Pet
    with custom axios instance
globalAxios POST /v2/pet HTTP/1.1
Accept: application/json, text/plain, */*
Content-Type: application/json
User-Agent: axios/1.6.1
Content-Length: 200
Accept-Encoding: gzip, compress, deflate, br
Host: petstore.swagger.io
Connection: close


      ✓ should add and delete Pet


  2 passing (36ms)

Notice how the interceptor does not log the response from the 'without custom axios instance' test suite since that instance does not have an interceptor. I was able to log the request headers by adding an interceptor to that globalAxios inside base.js in the with-npm-version build. That request does have my new header.

Sorry for the long response, but any insight you can provide here is appreciated, thanks!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the instance created in https://github.com/axios/axios/blob/415ca9440195586dcd2149aa6f1e99f0ff6957c2/lib/axios.js#L47 seems to be the same one for all importers of that exact node module. without having tried it, I guess you might have tested scenarios where there were multiple axios packages inside the node_modules folder. In order to avoid side-effects of importing the generated code here, I suggest to just add it to the configuration somewhere

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated to add it to the configuration, let me know what you think

@ckoegel
Copy link
Contributor Author

ckoegel commented Dec 3, 2024

hey, @joscha @macjohnny
any update on this?

Copy link
Member

@macjohnny macjohnny left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, looks safer now :-)

please address the minor comment (and update the samples after that), then we can merge.

this.baseOptions = param.baseOptions;
this.baseOptions = {
...param.baseOptions,
headers: {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please move this before the ...param.baseOptions, so it can be overridden

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ckoegel actually thinking about it again, how about changing this to

this.baseOptions = {
            ...param.baseOptions,
            headers: {
                'User-Agent': "OpenAPI-Generator{{#npmVersion}}/{{npmVersion}}{{/npmVersion}}/typescript-axios",
                ...param.baseOptions?.headers,
            },
        };

in a separate pull request?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you like me to open a PR with this change and we can get that into the 7.12.0 milestone?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DavidWittman opened #20571, which should address the issue

@macjohnny macjohnny merged commit 289425b into OpenAPITools:master Dec 17, 2024
19 checks passed
@wing328 wing328 added this to the 7.11.0 milestone Jan 20, 2025
@anri-asaturov
Copy link

anri-asaturov commented Jan 21, 2025

This change generates tons of Refused to set unsafe header "User-Agent" in Chrome.
--http-user-agent is not changing the default one, am I missing something?

@macjohnny
Copy link
Member

@anri-asaturov thanks for reporting this issue! @ckoegel i would suggest to revert this PR and leave it up to users to set a user agent header via the config if they need it. @joscha any objections?

@anri-asaturov
Copy link

There is a workaround to create and pass your own Configuration instance.

const cfg = new Configuration({
  baseOptions: {
    withCredentials: true,
    headers: {
      'User-Agent': null
    }
  }
});

export const auth = new AuthApi(cfg);

Any other ways to change useragent failed. Javascript generator had similar issue not so long ago.

DavidWittman added a commit to DavidWittman/openapi-generator that referenced this pull request Feb 1, 2025
The change in OpenAPITools#20067 has caused some issues with clients which run in a
Browser. This commit replaces that change, leaving the default
User-Agent for axios unmodified, and only sets the User-Agent if the
`http-user-agent` parameter is provided during generation time.
DavidWittman added a commit to DavidWittman/openapi-generator that referenced this pull request Feb 1, 2025
The change in OpenAPITools#20067 has caused some issues with clients which run in a
Browser. This commit replaces that change, leaving the default
User-Agent for axios unmodified, and only sets the User-Agent if the
`http-user-agent` parameter is provided during generation time.
DavidWittman added a commit to DavidWittman/openapi-generator that referenced this pull request Feb 3, 2025
The change in OpenAPITools#20067 has caused some issues with clients which run in a
Browser. This commit replaces that change, leaving the default
User-Agent for axios unmodified, and only sets the User-Agent if the
`http-user-agent` parameter is provided during generation time.
macjohnny pushed a commit that referenced this pull request Feb 3, 2025
The change in #20067 has caused some issues with clients which run in a
Browser. This commit replaces that change, leaving the default
User-Agent for axios unmodified, and only sets the User-Agent if the
`http-user-agent` parameter is provided during generation time.
timon-sbr pushed a commit to timon-sbr/openapi-generator that referenced this pull request Mar 13, 2025
…ools#20067)

* [typescript-axios] Add User-Agent Header to Default Axios

* fix if `npmVersion` doesn't exist

* generate samples

* single line solution

* move user agent header to config

* generate samples

* splat for headers as well

* samples

* move headers above baseOptions

* samples

* commas are hard

* samples again
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants