This repository provides a comprehensive implementation of JWT authentication using Node.js, Express, and MySQL. The project showcases best practices in user registration, login, token-based authentication, and protected routes, all while maintaining robust error handling and logging mechanisms.
- Features
- Tech Stack
- Prerequisites
- Setup
- API Endpoints
- Error Handling
- Logging
- Contributing
- License
- Links
- User Registration: Secure user registration with bcrypt password hashing.
- User Login: JWT token generation for authenticated users.
- Protected Routes: Middleware-enforced JWT protection for sensitive routes.
- Error Handling: Centralized error management with detailed logging using Winston.
- Backend: Node.js, Express
- Database: MySQL
- Authentication: JWT (JSON Web Tokens)
- Logging: Winston
- Environment Management: dotenv
Ensure you have the following installed and configured on your machine:
- Node.js: Version 14 or higher. Download here.
- MySQL: MySQL server or a compatible database. Download here.
For installation assistance, refer to the official documentation or guides.
-
Clone the repository:
git clone https://github.com/AchrefDevTN/jwt-auth-starter.git
-
Navigate into the project directory:
cd jwt-auth-starter -
Install dependencies:
npm install
-
Create a .env file in the root directory: (Copy the contents below and configure your environment variables)
PORT=5000 JWT_SECRET=your_jwt_secret JWT_EXPIRATION=1h DB_USERNAME=root DB_PASSWORD=your_db_password DB_NAME=jwt_auth_db DB_HOST=localhost
-
Run the application:
- For development
npm run dev
- For production
npm start
-
Access the API:
- The server will be running on
http://localhost:5000
-
POST
/api/auth/register
Registers a new user.
Request body:{ "username": "string", "password": "string" }Response:
{ "message": "User registered successfully" } -
POST
/api/auth/login
Logs in a user and returns a JWT token.
Request body:{ "username": "string", "password": "string" }Response:
{ "token": "jwt_token_string" } -
GET
/api/auth/protected
Access a protected route (JWT required in the Authorization header).
Response:{ "message": "This is a protected route", "userId": "user_id" }
Errors are handled centrally in the middleware. If an error occurs, the server responds with an appropriate status code and message. All errors are logged using Winston for debugging and monitoring purposes.
The application uses Winston for logging. Logs are written to both the console and a file named app.log.
If you have suggestions or improvements, please submit an issue or pull request. Contributions are welcome!
This project is licensed under the MIT License. See the LICENSE file for details.
| Node.js | Express | MySQL | License |
|---|---|---|---|
