A simple Node.js and Express.js REST API that demonstrates JWT (JSON Web Token) Authentication using Express Middleware. This project provides a protected endpoint that can only be accessed with a valid JWT token.
- JWT-based Authentication
- Protected API Endpoint
- Express Middleware for Token Verification
- RESTful API Design
- Proper Error Handling
- JSON Responses
- Node.js
- Express.js
- JSON Web Token (JWT)
- JavaScript (ES6)
jwt-auth-api/
│
├── middleware/
│ └── auth.js
│
├── routes/
│ └── protected.js
│
├── server.js
├── package.json
├── package-lock.json
└── .gitignore
git clone https://github.com/<your-username>/jwt-auth-api.gitcd jwt-auth-apinpm installnode server.jsor
npx nodemon server.jsThe server will start at:
http://localhost:5000
POST
/api/login
{
"token": "your_generated_jwt_token"
}GET
/api/protected
Authorization: Bearer <your_jwt_token>
{
"message": "Protected Resource Accessed Successfully",
"user": {
"id": 1,
"username": "Akansha"
}
}{
"message": "Token missing"
}{
"message": "Invalid Token"
}- Client sends a POST request to
/api/login. - Server generates a JWT using
jwt.sign(). - Client receives the JWT token.
- Client includes the token in the
Authorizationheader. - Authentication middleware verifies the token using
jwt.verify(). - If the token is valid, access to the protected route is granted.
- If the token is missing or invalid, the server returns 401 Unauthorized.
You can test the API using:
- Postman
- Thunder Client
- Insomnia
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
- JWT Authentication
- Express Middleware
- REST API Development
- Route Protection
- Authorization Header Handling
- JSON Responses
- Error Handling
This project was developed as part of a technical interview assessment to demonstrate JWT Authentication using Node.js and Express.js.