A robust JWT (JSON Web Token) utility library built on top of the Jose library.
@nowarajs/jwt provides a simple and powerful API for signing and verifying JSON Web Tokens with built-in error handling, human-readable time expressions, and comprehensive JWT claims management. Built with TypeScript and optimized for Bun runtime.
bun add @nowarajs/jwt @nowarajs/error
import { signJWT, verifyJWT } from '@nowarajs/jwt'
// Sign a JWT with default 15-minute expiration
const secret = 'your-secret-key'
const payload = { userId: '123', role: 'user' }
const token = await signJWT(secret, payload)
// Verify the JWT
const result = await verifyJWT(token, secret)
if (result)
console.log('Valid token:', result.payload)
else
console.log('Invalid or expired token')
import { signJWT } from '@nowarajs/jwt'
const token = await signJWT(
'your-secret-key',
{
userId: '123',
role: 'admin',
permissions: ['read', 'write'],
// Override default claims
iss: 'MyApp',
sub: 'user-123',
aud: ['web-app', 'mobile-app']
},
'2 hours' // Human-readable expiration
)
The library supports various expiration formats:
// Numeric timestamp (seconds since epoch)
await signJWT(secret, payload, 1672531200)
// Date object
await signJWT(secret, payload, new Date('2024-12-31'))
// Human-readable strings
await signJWT(secret, payload, '15 minutes')
await signJWT(secret, payload, '2 hours')
await signJWT(secret, payload, '1 day')
await signJWT(secret, payload, '1 week')
await signJWT(secret, payload, '30 days')
// With modifiers
await signJWT(secret, payload, '+2 hours')
await signJWT(secret, payload, '1 hour from now')
import { signJWT, verifyJWT } from '@nowarajs/jwt'
import { HttpError } from '@nowarajs/error'
try {
const token = await signJWT('secret', { userId: '123' }, '-1 hour') // Past expiration
} catch (error) {
if (error instanceof HttpError) {
console.log('JWT Error:', error.message)
console.log('Status Code:', error.httpStatusCode)
}
}
You can find the complete API reference documentation for jwt
at:
Distributed under the MIT License. See LICENSE for more information.