Get npm package latest version from a gitlab registry

/help
I’m trying to put a package in a Gitlab registry using npm and .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?

This is really fiddly to get right, and I found the documentation to be confusing, but I think your config lines should be:

  - npm config set @${CI_PROJECT_ROOT_NAMESPACE}:registry ${CI_API_V4_URL}/packages/npm/
  - npm config set -- //${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken ${CI_JOB_TOKEN}
  - npm config set always-auth true

The = signs you have there are only needed if you are writing directly into the .npmrc file, but the npm config set command should add them for you.

1 Like