Home > OS >  Get npm package latest version from a gitlab registry
Get npm package latest version from a gitlab registry

Time:07-06

I'm trying to put a package in a Gitlab registry using npm and .gitlab-ci.yml.

.gitlab-ci.yml

npm-package:
  stage: build
  image: node:buster
  before_script:
    - git config --global user.name "${GITLAB_USER_NAME}"
    - git config --global user.email "${GITLAB_USER_EMAIL}"
  script:
    - npm config set @${CI_PROJECT_ROOT_NAMESPACE}:registry=https://${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/
    - npm config set //${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}
    - NPM_PACKAGE_NAME=$(node -p "require('.package.json').name")
    - NPM_PACKAGE_VERSION=$(node -p "require('./package.json').version")
    - echo $(npm view "${NPM_PACKAGE_NAME}" versions)
    - echo ${NPM_PACKAGE_NAME}
    - echo ${NPM_PACKAGE_VERSION}
    - |
      if [[ $(npm view "${NPM_PACKAGE_NAME}" versions) != *"'${NPM_PACKAGE_VERSION}'"* ]]; then
        npm config set //${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken=${CI_JOB_TOKEN}
        npm publish
        echo "Successfully published version ${NPM_PACKAGE_VERSION} of ${NPM_PACKAGE_NAME} to GitLab's NPM registry: ${CI_PROJECT_URL}/-/packages"
      else
        echo "Version ${NPM_PACKAGE_VERSION} of ${NPM_PACKAGE_NAME} has already been published, so no new version has been published."
      fi

I tried my first time and the package was saved successfully in the repo. And now I'm trying to run it under the condition: if the version's package has changed then run an npm publish. But the variable $(npm view "${NPM_PACKAGE_NAME}" versions) seems to be empty, and when I try to echo it I get the error:

npm ERR! code E401

npm ERR! 401 Unauthorized - GET https://gitlab.example.com/api/v4/projects/1/packages/npm/@my_scope/my_package

Any help?

CodePudding user response:

Your CI does not have enough rights.

1- You need to generate an access token (automation type) from your npm registry via the npm UI (or via the command line).

The process with the UI: https://docs.npmjs.com/creating-and-viewing-access-tokens

2- Assign the token to an environment variable (named NPM_TOKEN in this example) accessible to your CI

3- Then create (or update) a .npmrc file with this line at the top: //registry.npmjs.org/:_authToken=${NPM_TOKEN}

  • Related