Skip to content
>GLB_
Go back

Resolving the Node.js Error: Cannot find module jsonwebtoken

When developing backend services with Node.js, especially APIs that implement authentication, it is common to rely on JSON Web Tokens (JWT). One frequent runtime error encountered in this context is:

Error: Cannot find module 'jsonwebtoken'
code: 'MODULE_NOT_FOUND'

This article explains the root cause of this error and provides a precise, production-oriented solution.


Problem Description

The error indicates that Node.js cannot resolve the jsonwebtoken module at runtime. In practical terms, this means that:

The stack trace typically points to files such as:

This confirms that the module is required during application startup.


Root Cause

Node.js resolves dependencies based on the nearest node_modules directory relative to the executing file. If jsonwebtoken is missing from that dependency tree, the runtime fails immediately.

This is especially common in:


Correct Solution

1. Install the dependency in the correct package

Navigate to the directory where your backend application is defined (the same directory that contains package.json for app.js):

cd backend
npm install jsonwebtoken

For other package managers:

yarn add jsonwebtoken

pnpm -F backend add jsonwebtoken

2. Verify installation

Ensure the dependency is listed as a runtime dependency:

npm ls jsonwebtoken

And confirm package.json contains:

"dependencies": {
  "jsonwebtoken": "^9.x"
}

It must not be under devDependencies.


3. Verify import syntax

Use the correct import style based on your module system.

CommonJS (default in Node.js):

const jwt = require('jsonwebtoken');

ES Modules:

import jwt from 'jsonwebtoken';

Mixing module systems can also cause runtime failures.


4. Restart the application

If using nodemon, it will automatically restart once dependencies are installed. Otherwise:

node src/app.js

Additional Troubleshooting

If the error persists:

rm -rf node_modules package-lock.json
npm ci

Conclusion

The Cannot find module 'jsonwebtoken' error is not related to JWT logic itself but to dependency resolution. Installing the package in the correct scope and verifying runtime dependencies resolves the issue cleanly.

This class of error reinforces the importance of explicit dependency management, particularly in modular or workspace-based Node.js projects.


Share this post:

Previous Post
Why Small Tables Can Explode: Understanding JOIN Cardinality in SQL
Next Post
Sending Athena Query Results to Amazon SQS: Architecture, Costs, and Limitations