DEV Community

Cover image for Using pnpm with the GitLab package registry in GitLab CI
Daniel Bayerlein
Daniel Bayerlein

Posted on

Using pnpm with the GitLab package registry in GitLab CI

In this blog post, I explain how to use pnpm in GitLab CI and how to authenticate with a private GitLab package registry.

Corepack is an experimental tool that helps you manage the versions of your package managers.

package.json

The packageManager field specifies which package manager is expected to be used. The value is set to pnpm with the preferred version 8.15.4.

{
  "packageManager": "pnpm@8.15.4"
}
Enter fullscreen mode Exit fullscreen mode

.gitlab-ci.yml

In order to have pnpm available in every job, it is installed within the before_script. These commands are executed before each job!

before_script:
  - corepack enable
  - corepack prepare --activate
Enter fullscreen mode Exit fullscreen mode

To also use the cache, it is configured as follows:

cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - .pnpm-store
  policy: pull-push

before_script:
  - pnpm config set store-dir .pnpm-store
Enter fullscreen mode Exit fullscreen mode

The following commands are required to access the private package registry:

before_script:
  - pnpm config set @scope:registry https://${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/
  - pnpm config set -- //${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken ${CI_JOB_TOKEN}
Enter fullscreen mode Exit fullscreen mode

Replace @scope with your package scope. The environment variables CI_SERVER_HOST, CI_PROJECT_ID and CI_JOB_TOKEN are provided by GitLab CI. You do not need to manually create and set a token for the package registry. The CI_JOB_TOKEN is valid as long as the job is running.

Packages can now be downloaded and published.

Complete code example

With this example you can use pnpm in GitLab CI, download packages from the GitLab package registry and also publish them.

.gitlab-ci.yml

image: 'public.ecr.aws/docker/library/node:18-bullseye'

stages:
  - build
  - deploy

cache:
  key: $CI_COMMIT_REF_SLUG
  paths:
    - .pnpm-store
  policy: pull-push

before_script:
  - corepack enable
  - corepack prepare --activate
  - pnpm config set store-dir .pnpm-store
  - pnpm config set @scope:registry https://${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/
  - pnpm config set -- //${CI_SERVER_HOST}/api/v4/projects/${CI_PROJECT_ID}/packages/npm/:_authToken ${CI_JOB_TOKEN}
  - pnpm install

build:
  stage: build
  script:
    - pnpm run build
  artifacts:
    paths:
      - dist/

publish:
  stage: deploy
  needs:
    - job: build
  script:
    - pnpm publish
Enter fullscreen mode Exit fullscreen mode

If you have any kind of feedback, suggestions or ideas - feel free to comment this post!

Top comments (0)