CodexBloom - Programming Q&A Platform

GitHub Actions: How to cache dependencies for a Node.js project to speed up builds?

👀 Views: 232 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
github-actions caching node.js yaml

I'm trying to debug I'm relatively new to this, so bear with me..... I'm currently working on a Node.js project and using GitHub Actions for CI/CD. I've set up a workflow that installs dependencies, runs tests, and builds the project. However, I've noticed that every time the workflow runs, it takes a significant amount of time because it's re-installing all the dependencies. I want to implement caching to speed up these builds but I'm not sure how to do it correctly. The workflow file looks like this: ```yaml name: CI on: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 - name: Setup Node.js uses: actions/setup-node@v2 with: node-version: '14' - name: Install dependencies run: npm install - name: Run tests run: npm test - name: Build project run: npm run build ``` I read that I can use `actions/cache` to cache the `node_modules` folder, but I'm unsure where to place it in the workflow and how to properly configure the cache key. Here's what I attempted, but it seems to be storing cache incorrectly: ```yaml - name: Cache Node.js modules uses: actions/cache@v2 with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- ${{ runner.os }}- ``` I still see the message `Cache not found for input keys: ...` even after I push changes. I've verified that my `package-lock.json` file is in the root directory, but it seems like the cache isn't being utilized on subsequent runs. What am I doing wrong here? How can I ensure that the cache works as intended to reduce build times? I'd really appreciate any guidance on this. This is for a web app running on Ubuntu 20.04. Any ideas what could be causing this? This issue appeared after updating to Yaml LTS. I'm open to any suggestions.