jose library for JWKS fetching and JWT verification.
Installation
Install the required dependencies:express: Web framework for Node.jsjose: Modern JavaScript implementation of JOSE standards (JWT, JWK, JWS, etc.)
Basic Example
Here’s a complete Express.js server with JWT verification:index.js
package.json to use ES modules:
package.json
Middleware Pattern
Create reusable auth middleware with better error handling:middleware/auth.js
index.js
TypeScript Example
For better type safety, use TypeScript:src/index.ts
tsconfig.json
package.json
Error Handling
Implement comprehensive error handling:middleware/errorHandler.js
Configuration Management
Use environment variables with validation:config/index.js
Testing
Test your JWT verification with Jest:__tests__/auth.test.js
Environment Variables
Create a.env file for development:
.env
dotenv:
index.js
Production Deployment
Docker Example
Dockerfile
Using PM2
For production process management:ecosystem.config.js
CORS Configuration
If your frontend is on a different domain:Common Issues
'Cannot use import statement outside a module'
'Cannot use import statement outside a module'
Add Or rename files to
"type": "module" to your package.json:.mjs extension.'Invalid signature' error
'Invalid signature' error
Verify:
- JWKS URL is correct and accessible
- Issuer and audience match Better Auth URL
- Token was issued by the correct instance
CORS errors
CORS errors
Install and configure
cors middleware:Token expired errors
Token expired errors
JWTs have limited lifetime. The frontend
api-client.ts automatically refreshes tokens with a 10-second buffer before expiration.Next Steps
Go Example
See how to implement JWT verification in Go
Python Example
Learn how to verify JWTs in Python with Flask