@codesled/auth
v1.0.3
Published
Reusable authentication logic for Node.js apps. Includes password hashing, login validation, and JWT token generation. Framework-agnostic and database-agnostic — plug into any stack.
Readme
@codesled/auth
Reusable authentication logic for Node.js apps. Includes password hashing, login validation, and JWT token generation. Framework-agnostic and database-agnostic — plug into any stack.
🔗 View example project using this package: CodeSled Auth Demo
Features
- Hashes passwords using bcrypt
- Validates login by comparing hashed passwords
- Generates JWT access tokens
- Optional Express middleware for route protection
- Works with any database or ORM (not opinionated)
Installation
npm install @codesled/authRequires
dotenvif you want to load JWT secrets from an.envfile.
Environment Setup
Create a .env file in your root directory and add:
JWT_SECRET=your_super_secret_jwt_keyOr set process.env.JWT_SECRET manually in your code.
Usage Example
Registering a User
import { registerUser } from '@codesled/auth';
const result = await registerUser('[email protected]', 'securepassword');
// Save result.hashed to your own database
console.log(result);
// { email: '[email protected]', hashed: '$2a$10$...' }Logging In a User
import { loginUser } from '@codesled/auth';
// Retrieve user's hashed password from your DB
const storedHash = getUserFromDB().hashed;
const token = await loginUser('[email protected]', 'securepassword', storedHash);
console.log('JWT Token:', token);Protecting Routes (Express Example)
import express from 'express';
import { authenticate } from '@codesled/auth';
const app = express();
app.get('/protected', authenticate, (req, res) => {
res.send(`Welcome, ${req.user.email}`);
});Composable Functions
| Function | Purpose |
|-------------------|-------------------------------------------|
| registerUser | Hashes password and returns object |
| loginUser | Validates password and returns JWT token |
| hashPassword | Hash-only utility |
| comparePassword | Compare plain password with hash |
| generateToken | Create a new JWT token |
| authenticate | Express middleware to protect routes |
Local Testing
Try it directly with:
node test-auth.mjsEnsure you have:
.envfile withJWT_SECRET- Dependencies installed via
pnpm install
License
MIT — Free for personal and commercial use.
