jwtmoshiur
v1.1.3
Published
JWT auto-setup package with token generation and verification
Downloads
1,171
Maintainers
Readme
Video Tutorial
Video
JWT Moshiur
JWT Moshiur is a zero-configuration npm package for quickly adding JWT token generation and verification to Node.js applications. It creates the necessary project files automatically and keeps integration simple.
Overview
JWT Moshiur simplifies JWT integration by generating a .env file and utility scripts during installation. The package supports both JavaScript and TypeScript projects, so you can begin issuing and validating tokens with minimal setup.
Installation
npm install jwtmoshiurOnce installation completes, run the setup command to generate configuration and utility files:
npx jwtmoshiurAfter this command, your project will contain:
.envwith JWT configurationutils/generateToken.jsorutils/generateToken.tsutils/verifyToken.jsorutils/verifyToken.ts
Quick Start
Generate a Token
const { generateToken } = require('./utils/generateToken');
const token = generateToken({
userId: '12345',
email: '[email protected]',
role: 'admin'
});
console.log(token);Verify a Token
const { verifyToken } = require('./utils/verifyToken');
try {
const decoded = verifyToken(token);
console.log(decoded);
} catch (error) {
console.error('Token is invalid or expired');
}Usage Examples
Express.js Authentication Middleware
const express = require('express');
const { verifyToken } = require('./utils/verifyToken');
const { generateToken } = require('./utils/generateToken');
const app = express();
const authMiddleware = (req, res, next) => {
const authorization = req.headers.authorization;
const token = authorization ? authorization.split(' ')[1] : null;
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
req.user = verifyToken(token);
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
};
app.post('/login', (req, res) => {
const user = { id: 1, email: '[email protected]' };
const token = generateToken(user);
res.json({ token });
});
app.get('/profile', authMiddleware, (req, res) => {
res.json({ user: req.user });
});
app.listen(3000, () => console.log('Server running on port 3000'));Simple Async/Await Example
const { generateToken, verifyToken } = require('./utils');
async function authenticateUser(credentials) {
const token = generateToken({
userId: credentials.id,
email: credentials.email,
timestamp: Date.now()
});
const payload = verifyToken(token);
console.log('Authenticated user:', payload.email);
return payload;
}Custom Token Expiry
const { generateToken } = require('./utils/generateToken');
const token = generateToken({ userId: '123' });Token expiry is controlled by JWT_EXPIRY in .env.
Configuration
Update your .env file to customize JWT settings:
# JWT Moshiur Configuration
JWT_SECRET=your-super-secret-key-change-this-in-production
JWT_EXPIRY=24hEnvironment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| JWT_SECRET | Generated | Secret used to sign tokens |
| JWT_EXPIRY | 24h | Token expiry period |
Use a strong, unique secret in production.
API Reference
generateToken(payload: object): string
Generates a signed JWT token.
Example:
const token = generateToken({
userId: '123',
email: '[email protected]',
role: 'user'
});verifyToken(token: string): object
Verifies a JWT token and returns the decoded payload.
Example:
try {
const payload = verifyToken(token);
console.log('Valid token:', payload);
} catch (error) {
console.error('Invalid token:', error.message);
}Manual Setup
If you need to run setup again:
npx jwtmoshiurProject Structure
After setup, your project will include:
your-project/
├── .env
├── utils/
│ ├── generateToken.js
│ └── verifyToken.js
├── node_modules/
│ └── jwtmoshiur/
└── package.jsonSecurity Guidelines
- Do not commit
.envto source control. - Use a strong JWT secret.
- Rotate secrets periodically.
- Use HTTPS in production.
- Choose an expiry period that fits your security requirements.
Troubleshooting
Setup did not run automatically
Run:
npx jwtmoshiurToken verification fails
- Confirm
JWT_SECRETis present in.env - Confirm token has not expired
- Confirm the token was generated with the same secret
.env file is missing
Run the setup command manually and verify the file exists.
License
MIT
Issue: Auto setup not working after npm install
Solution: Manually run the setup command:
npx jwtmoshiurOr if you're in the package, run:
npm exec jwtmoshiurOr update to v1.0.1+:
npm install jwtmoshiur@latestIssue: Token generation fails
Solution: Ensure JWT_SECRET is set in .env
Issue: "Invalid token" error
Solution: Verify the token hasn't expired or been tampered with
Issue: .env not created
Solution: Run npx jwtmoshiur to manually trigger setup
Requirements
- Node.js >= 14.0.0
- npm >= 6.0.0
Dependencies
jsonwebtoken- JWT signing and verificationdotenv- Environment variable management
License
MIT License - see LICENSE file for details
Author
Created by Moshiur Rahman Deap Portfolio - (Moshiur Rahman Deap)[https://moshiurrahman.online]
Contributing
Contributions are welcome! Feel free to submit issues and pull requests.
Support
If you have any questions or issues, please open an issue on GitHub or contact the maintainer.
Happy coding! 🎉

