Build secure user registration and authentication backend using Node.js, Express, and PostgreSQL with security best practices
Build a secure user registration and authentication backend using Node.js, Express, and PostgreSQL following security best practices.
When working on this Node.js backend project, follow these guidelines:
1. **Technology Stack**
- Use Node.js with Express framework for the API server
- Use PostgreSQL as the database
- Implement user registration (cadastro) and login (autenticação) functionality
2. **Security Best Practices**
- Hash passwords using bcrypt before storing in the database
- Use parameterized queries or an ORM (like Sequelize or TypeORM) to prevent SQL injection
- Implement JWT tokens for authentication
- Validate and sanitize all user inputs
- Use environment variables for sensitive configuration (database credentials, JWT secrets)
- Implement rate limiting for authentication endpoints
- Use HTTPS in production
3. **Database Safety**
- Always use prepared statements or parameterized queries
- Never concatenate user input directly into SQL queries
- Implement proper error handling that doesn't expose database structure
- Use connection pooling for better performance
- Apply the principle of least privilege to database users
4. **Code Organization**
- Separate routes, controllers, and models
- Use middleware for authentication and validation
- Implement proper error handling middleware
- Keep configuration in separate files
- Use async/await for database operations
5. **API Endpoints**
- POST `/api/auth/register` - User registration
- POST `/api/auth/login` - User login
- Use appropriate HTTP status codes
- Return consistent JSON response formats
6. **Password Requirements**
- Enforce minimum password length (at least 8 characters)
- Consider requiring mix of uppercase, lowercase, numbers, and special characters
- Store only hashed passwords with salt
7. **Session Management**
- Use JWT tokens with appropriate expiration times
- Implement token refresh mechanism if needed
- Store minimal necessary data in tokens
```javascript
// Example: Secure password hashing
const bcrypt = require('bcrypt');
const saltRounds = 10;
async function hashPassword(plainPassword) {
return await bcrypt.hash(plainPassword, saltRounds);
}
// Example: Safe database query with parameterization
async function createUser(email, hashedPassword) {
const query = 'INSERT INTO users (email, password) VALUES ($1, $2) RETURNING id';
const values = [email, hashedPassword];
return await pool.query(query, values);
}
// Example: JWT token generation
const jwt = require('jsonwebtoken');
function generateToken(userId) {
return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '24h' });
}
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/nodejs-auth-backend-with-express-and-postgresql/raw