jwt-auth-express-tidb-cloud
v1.0.5
Published
A comprehensive JWT authentication package for Express.js with TiDB Cloud support and automatic table creation.
Downloads
3
Maintainers
Readme
jwt-auth-express-tidb-cloud
A robust, production-ready JWT authentication package for Express.js with support for MySQL, MySQL2, and TiDB Cloud.
Features
- ✅ User registration & authentication
- ✅ JWT access & refresh tokens
- ✅ Password reset functionality
- ✅ Multiple database support (MySQL2, TiDB Cloud)
- ✅ Automatic table creation
- ✅ Comprehensive security features
- ✅ Production-ready error handling
Quick Start
A focused, production-ready JWT authentication library and example server for Express.js. It provides common auth flows (signup, signin, refresh tokens, password reset) and supports MySQL2 backends (TiDB Cloud). This repo is organized so you can reuse the service code or run the example server directly.
Highlights
- Access & Refresh token support (JWT)
- Signup / Signin / Signout
- Refresh token rotation
- Forgot / Reset password via email (pluggable email provider)
- Database-agnostic configuration with TiDB Cloud optimizations
- Minimal, testable controller + middleware structure
Quick start (example)
Install dependencies and run the example server:
git clone https://github.com/ZaheerAhmedkhan65/jwt-auth-express-tidb-cloud.git
cd jwt-auth-express-tidb-cloud
npm install
# copy .env.example to .env and edit values
node index.js
or
npm run devThe example server exposes authentication endpoints under /auth (see API section).
Installation (library)
This repository can be used as a library or as a standalone example. To install from npm:
npm install jwt-auth-express-tidb-cloudOr use the code directly in your project by importing the controller/router modules.
Use (express server)
app.js
require('dotenv').config();
const express = require('express');
const JwtAuthExpress = require('jwt-auth-express-tidb-cloud');
const cors = require('cors');
const app = express();
// Middlewares
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
async function startServer() {
// Initialize auth with UI enabled
const auth = await JwtAuthExpress.create({
secret: process.env.ACCESS_TOKEN_SECRET,
refreshSecret: process.env.REFRESH_TOKEN_SECRET,
database: {
host: process.env.TIDB_HOST,
database: process.env.TIDB_DATABASE,
username: process.env.TIDB_USERNAME,
password: process.env.TIDB_PASSWORD
},
basePath: '/o/auth', // Customize path
enableUI: true // Enable built-in UI
});
auth.setupApp(app);
app.listen(3000, () => {
console.log('Server running on port 3000');
console.log('Authentication UI: http://localhost:3000/o/auth/signin');
});
}
startServer();Test
npm startThis will start the server at http://localhost:3000
You have to type in browser's search bar /0/auth/signin to visit signin page generated by jwt-auth-express-tidb-cloud package.
Configuration
The project expects configuration via environment variables. Common variables used by this repository:
- NODE_ENV — runtime environment (development|production)
- PORT — HTTP port (default: 3000)
- ACCESS_TOKEN_SECRET — secret used to sign access tokens
- REFRESH_TOKEN_SECRET — secret used to sign refresh tokens
- TIDB_USERNAME=your_db_user.root
- TIDB_PASSWORD=your_db_password
- TIDB_PORT=4000 (default)
- TIDB_DATABASE=db_name
- TIDB_HOST=your_db_host
Create a .env file or pass env vars to your process. Example .env (for development):
NODE_ENV=development
PORT=3000
ACCESS_TOKEN_SECRET=replace_with_a_strong_secret
REFRESH_TOKEN_SECRET=replace_with_a_different_strong_secret
TIDB_USERNAME=your_db_user.root
TIDB_PASSWORD=your_db_password
TIDB_PORT=4000 (default)
TIDB_DATABASE=db_name
TIDB_HOST=your_db_hostNotes:
- TiDB Cloud connections require SSL configuration — see
src/config/database.jsfor details. - Secrets must be long, unpredictable strings in production. Consider using a secrets manager.
API (Auth routes)
All endpoints live under the /auth route in the example server. Routes exposed by src/routes/authRoutes.js:
POST /auth/signup — Register a new user
- body: { email, password, name }
- returns: user object and tokens
POST /auth/signin — Authenticate a user
- body: { email, password }
- returns: user object and tokens
POST /auth/refresh-token — Rotate refresh token and get new access token
- body: { refreshToken }
- returns: { accessToken, refreshToken }
POST /auth/forgot-password — Request a password reset
- body: { email }
- returns: generic success message (no user enumeration)
POST /auth/reset-password — Reset password using token
- body: { token, userId, newPassword }
- returns: success message
POST /auth/signout — Sign out (remove refresh token)
- body: { refreshToken }
GET /auth/me — Get current authenticated user (protected)
- headers: Authorization: Bearer
- returns: current user
Example curl (signup):
curl -X POST http://localhost:3000/auth/signup \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"supersecret","name":"Me"}'Example curl (signin):
curl -X POST http://localhost:3000/auth/signin \
-H "Content-Type: application/json" \
-d '{"email":"[email protected]","password":"supersecret"}'Integration & tests
Run the test suite (project uses a small integration test):
npm testIf the tests require a database, ensure the database env vars point to a running test database. The repo includes tests/integration.test.js as a starting point.
Development
- Install dev dependencies:
npm install - Run the server locally:
node index.js(or use nodemon) - Lint and format as needed (no linter configured in this repo by default)
Project layout (important files):
index.js— example server bootstrapsrc/controllers— auth controller logicsrc/routes— express routes wiringsrc/middleware— auth + validation middlewaresrc/models— user model / DB helperssrc/utils— jwt, crypto, email helpers
Contributing
Contributions are welcome. To contribute:
- Fork the repository
- Create a topic branch:
git checkout -b feat/your-feature - Commit changes with clear messages
- Open a pull request describing the change
Please include tests for new behavior and keep changes focused.
Security
- Keep
ACCESS_TOKEN_SECRETandREFRESH_TOKEN_SECRETout of source control. - Rotate secrets on suspected compromise and invalidate refresh tokens where appropriate.
- Use HTTPS in production and secure cookie flags if you add cookie-based storage.
If you discover a security vulnerability, please open an issue or contact the maintainers directly.
License
This project is licensed under the MIT License — see the LICENSE file for details.
Acknowledgements
Inspired by common Express + JWT patterns. Thanks to contributors and the Node.js community.
