Prevent access token embedded in URL from replacing git credentials cache

Our npm project has a git dependency that is on a private server which needs credentials. Both the project and the dependency are hosted by the same server.

Using a git dependency with credentials caused all kinds of problems: auth errors, npm adding people’s usernames to the URL in package.json, etc.

To try and solve this, I generated a read-only access token and embedded it in the URL as a password.

  "dependencies": {
    "myPackage": "git+https://user:[email protected]`

This worked ok for running npm install, but then it replaced my cached git credentials (wincred) with the access token!

Is there a command I can run before and after the build to say something along the lines of: “Please temporarily don’t cache these credentials, but don’t forget the cache either?”

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

If you want to avoid having credentials saved to the credential helper, then you need to set the credential.helper option to the empty string. You can do that with a syntax like git -c credential.helper= clone URL, but that has to be used at the time the command is invoked, which will be difficult if it’s being invoked by npm.

Note that in general embedding credentials into URLs is insecure and you should avoid doing it. There has been discussion about dropping support for this on the Git list, in fact. You could try to use the example of reading from the environment in the Git FAQ using a custom configuration file. That file could look like this:

    helper =
    helper = "!f() { echo username=author; echo \"password=$GIT_TOKEN\"; };f"

and you could then (assuming your file is foo.cfg), set GIT_TOKEN in the environment and run GIT_CONFIG=foo.cfg npm. That assumes that npm does not strip its environment; if it does, then you’re out of luck.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply