I wasn't able to make the accepted answer work in a Docker container.
What worked for me was to set the Personal Access Token from github in a file .nextrc
ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n login $GITHUB_READ_TOKEN" > ~/.netrc
RUN npm install --only=production --force \
&& npm cache clean --force
RUN rm ~/.netrc
in package.json
"my-lib": "github:username/repo",