> ## Documentation Index
> Fetch the complete documentation index at: https://docs.loremstock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrating and Maintaining Third-Party npm Libraries

> Safely evaluate, install, use, and maintain npm packages. Covers semver, package.json vs package-lock.json, npm audit, and dependency management best practices.

Third-party libraries let you add complex features without writing everything from scratch. This page teaches you how to evaluate packages for quality and safety, install and organize them correctly, understand semantic versioning, and keep your dependencies secure over time.

## Why Use Third-Party Libraries

| Benefit                | Example                                                                 |
| ---------------------- | ----------------------------------------------------------------------- |
| Save development time  | `express` handles routing so you don't build an HTTP parser             |
| Battle-tested security | `bcrypt` is audited by thousands; your own hash function is not         |
| Community support      | Stack Overflow, GitHub issues, and tutorials exist for popular packages |
| Maintenance            | Security patches are released by package authors, not just you          |

<Warning>
  Every dependency you add is code you did not write but must trust. Always evaluate before installing.
</Warning>

## How to Evaluate a Package

Check these indicators before running `npm install`:

| Indicator        | Look For                          | Where to Check   |
| ---------------- | --------------------------------- | ---------------- |
| Weekly downloads | 100k+ indicates community trust   | npm package page |
| Last updated     | Within the last 6 months          | npm or GitHub    |
| GitHub stars     | 1k+ generally reliable            | GitHub repo      |
| Open issues      | Maintainer responsiveness         | GitHub issues    |
| License          | MIT, Apache-2.0, BSD (permissive) | npm page or repo |
| README quality   | Clear docs with examples          | GitHub repo      |

<Warning>
  Typosquatting: attackers publish packages named `expres`, `bcrpyt`, or `mongoos` to trick developers. Always verify the exact spelling from official documentation.
</Warning>

## Essential Backend Libraries

Memorize this table. These are tested in exams.

| Package               | Purpose                                      | Install                         |
| --------------------- | -------------------------------------------- | ------------------------------- |
| **express**           | Web framework: routing, middleware, requests | `npm install express`           |
| **mongoose**          | MongoDB ODM: schemas, models, validation     | `npm install mongoose`          |
| **jsonwebtoken**      | Create and verify JWT tokens                 | `npm install jsonwebtoken`      |
| **bcrypt**            | Hash and compare passwords                   | `npm install bcrypt`            |
| **dotenv**            | Load .env file into process.env              | `npm install dotenv`            |
| **cors**              | Enable cross-origin requests from browsers   | `npm install cors`              |
| **helmet**            | Set secure HTTP headers automatically        | `npm install helmet`            |
| **morgan**            | Log every HTTP request                       | `npm install morgan`            |
| **joi**               | Schema validation for JS objects             | `npm install joi`               |
| **express-validator** | Input validation middleware                  | `npm install express-validator` |
| **nodemailer**        | Send emails from Node.js                     | `npm install nodemailer`        |
| **multer**            | Handle file uploads (multipart/form-data)    | `npm install multer`            |

## Installing Packages

```bash theme={null}
# Production dependency (needed at runtime)
npm install express

# Development dependency (only for dev/testing)
npm install --save-dev nodemon jest

# Install from package.json (after cloning a repo)
npm install

# Install a specific version
npm install express@4.18.2
```

| Type              | When to Use          | Examples                  |
| ----------------- | -------------------- | ------------------------- |
| `dependencies`    | Runtime (production) | express, mongoose, bcrypt |
| `devDependencies` | Development only     | jest, nodemon, eslint     |

## package.json vs package-lock.json

| File                | Purpose                                 | Commit to Git? |
| ------------------- | --------------------------------------- | -------------- |
| `package.json`      | Lists direct deps with version ranges   | YES            |
| `package-lock.json` | Locks exact versions of entire dep tree | YES            |
| `node_modules/`     | Installed packages                      | NEVER          |

```bash theme={null}
# .gitignore
node_modules/
.env
```

<Note>
  `package-lock.json` ensures every developer and every deployment gets exactly the same versions. Never delete it.
</Note>

## Semantic Versioning (Semver)

npm packages use `MAJOR.MINOR.PATCH`:

| Number    | Type of Change                    | Example            |
| --------- | --------------------------------- | ------------------ |
| **MAJOR** | Breaking changes                  | `4.0.0` -> `5.0.0` |
| **MINOR** | New features, backward compatible | `4.1.0` -> `4.2.0` |
| **PATCH** | Bug fixes, backward compatible    | `4.2.1` -> `4.2.2` |

### Version Prefixes in package.json

| Prefix | Allows                  | Example                                |
| ------ | ----------------------- | -------------------------------------- |
| `^`    | Minor and patch updates | `^4.18.0` allows `4.19.0` NOT `5.0.0`  |
| `~`    | Patch updates only      | `~4.18.0` allows `4.18.1` NOT `4.19.0` |
| none   | Exact version           | `4.18.0` only                          |

## Security and Maintenance

### npm audit

```bash theme={null}
# Scan for known vulnerabilities
npm audit

# Fix automatically where patches exist
npm audit fix

# Force updates (may include breaking changes - test first!)
npm audit fix --force
```

### Check and Update Packages

```bash theme={null}
# See what has newer versions
npm outdated

# Update within version ranges in package.json
npm update

# Update a specific package to latest
npm install express@latest

# Remove an unused package
npm uninstall some-package
```

## Full Example: Express + cors + helmet

```javascript theme={null}
// app.js
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');

const app = express();

app.use(helmet());                             // Security headers
app.use(cors({ origin: 'http://localhost:3001' })); // Restrict CORS to frontend
app.use(morgan('combined'));                   // HTTP request logging
app.use(express.json());                       // Parse JSON bodies

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

app.listen(3000, () => console.log('Server running on port 3000'));
```

```bash theme={null}
npm install express cors helmet morgan
```

## Key Terms

| Term                | Definition                                                    |
| ------------------- | ------------------------------------------------------------- |
| **semver**          | Semantic versioning: MAJOR.MINOR.PATCH                        |
| **dependency**      | Package needed at runtime (in `dependencies`)                 |
| **devDependency**   | Package needed only during development (in `devDependencies`) |
| **peer dependency** | Package a library expects the host project to install         |
| **lock file**       | `package-lock.json` that pins exact installed versions        |
| **vulnerability**   | Known security flaw in a package, reported in npm audit       |

## Common Mistakes

<Accordion title="Committing node_modules to Git">
  node\_modules is large, platform-specific, and regenerable. Always add it to .gitignore. Only commit package.json and package-lock.json.
</Accordion>

<Accordion title="Ignoring npm audit warnings">
  High-severity vulnerabilities can expose your entire application. Run npm audit in your CI pipeline and fail the build on critical findings.
</Accordion>

<Accordion title="Installing a runtime package as devDependency">
  If bcrypt is in devDependencies, it won't be installed in production with `npm install --production` and your app will crash. Double check --save-dev vs regular install.
</Accordion>

<Accordion title="Running npm audit fix --force without testing">
  Forced fixes can upgrade major versions with breaking changes. Always run your test suite after force-fixing.
</Accordion>
