Overview
The T1 Component Library API uses JWT (JSON Web Tokens) for secure, stateless authentication. Tokens are issued upon successful registration or login and must be included in theAuthorization header for protected endpoints.
Tokens are valid for 7 days by default. This duration is configurable via the
JWT_EXPIRES_IN environment variable.How Authentication Works
The authentication system follows a standard JWT flow:Register or Login
Users register via
POST /api/auth/register or login via POST /api/auth/login. Both endpoints return a JWT token upon success.Receive JWT Token
The server generates a signed JWT token containing the user’s ID and email. This token is returned in the response.
Store Token Securely
The client application stores the token securely (e.g., in localStorage, sessionStorage, or httpOnly cookies).
Include Token in Requests
For protected endpoints, the client includes the token in the
Authorization header using the Bearer scheme.Token Structure
JWT tokens are generated using thejsonwebtoken library and contain the following payload:
JWT_SECRET environment variable and expires based on JWT_EXPIRES_IN (default: 7d).
Token Generation
Tokens are generated in the auth service:Obtaining a Token
There are two ways to obtain a JWT token:1. Register a New User
2. Login with Existing Credentials
Passwords are hashed using bcrypt with a salt factor of 10 before being stored in the database. See
server/src/models/User.model.ts:34-40 for the implementation.Using Tokens in Requests
Once you have a token, include it in theAuthorization header of your requests using the Bearer authentication scheme:
Example: Authenticated Request
JavaScript/Fetch Example
Axios Example
Authentication Middleware
The authentication middleware validates tokens for protected routes:Protected vs Public Endpoints
The API has both public and protected endpoints:Public Endpoints (No Token Required)
POST /api/auth/register- Register a new userPOST /api/auth/login- Login with credentialsPOST /api/components/track- Track component interactionGET /api/components/stats- Get usage statisticsGET /api/health- Health check
Protected Endpoints (Token Required)
GET /api/components/export/view- View paginated tracking dataGET /api/components/export- Export all tracking data
Protected routes are defined in
server/src/routes/components.routes.ts:13-14 using the authMiddleware.Token Expiration
Tokens expire after the duration specified inJWT_EXPIRES_IN (default: 7 days).
Handling Expired Tokens
When a token expires, the API returns a401 Unauthorized response:
- Detect the 401 status code
- Clear the stored token
- Redirect the user to the login page
- Prompt the user to log in again
Example Error Handler
Security Best Practices
Recommendations
-
Store Tokens Securely
- Use httpOnly cookies for web applications to prevent XSS attacks
- If using localStorage, be aware of XSS vulnerabilities
- Never store tokens in URL parameters
-
Use HTTPS in Production
- Always transmit tokens over HTTPS to prevent interception
- The API supports CORS for secure cross-origin requests
-
Implement Token Refresh
- Consider implementing a refresh token mechanism for long-lived sessions
- Prompt users to re-authenticate before performing sensitive operations
-
Validate Input
- All authentication endpoints use express-validator for input validation
- Passwords must be at least 6 characters (see
User.model.ts:24)
-
Monitor Failed Attempts
- Log failed authentication attempts for security monitoring
- The API uses Morgan for HTTP request logging
Common Authentication Errors
| Status | Error Message | Cause | Solution |
|---|---|---|---|
401 | Token de autenticación no proporcionado | Missing Authorization header | Include Authorization: Bearer <token> header |
401 | Token inválido o expirado | Invalid or expired JWT | Login again to obtain a new token |
401 | Usuario no encontrado | User was deleted after token was issued | Register or login again |
401 | Credenciales inválidas | Wrong email or password | Check credentials and try again |
400 | El email ya está registrado | Email already exists | Use a different email or login instead |
Authentication Flow Diagram
Here’s a visual representation of the authentication flow:Next Steps
Tracking Endpoints
Learn how to track component interactions
Export Endpoints
Explore data export capabilities