PromptBase
Upgrade
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
(claude-4-7-opus)
Token size
524
Example input
[FEATURE REQUEST]: User authentication with email and password registration, login, JWT session management, and protected route middleware [TECH STACK]: Node.js, Express, MongoDB, Mongoose, JWT, bcryptjs [USER TYPE]: End users registering and logging into a web application [OUTPUT FORMAT]: Separate files with complete working code and integration steps
Example output
FEATURE SUMMARY A user authentication system that handles email and password registration, login, session management, and logout. Used by end users to create and access their accounts securely. Solves the problem of building auth from scratch for every new project. FILE STRUCTURE /src /auth authController.js authMiddleware.js authRoutes.js /models User.js /utils hashPassword.js generateToken.js .env.example COMPLETE CODE // User.js const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ email: { type: String, required: [true, 'Email is required'], unique: true, lowercase: true, trim: true, match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email'] }, password: { type: String, required: [true, 'Password is required'], minlength: [8, 'Password must be at least 8 characters'] }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('User', userSchema); // hashPassword.js const bcrypt = require('bcryptjs'); const hashPassword = async (password) => { try { const salt = await bcrypt.genSalt(12); return await bcrypt.hash(password, salt); } catch (error) { throw new Error('Password hashing failed'); } }; const comparePassword = async (password, hashedPassword) => { try { return await bcrypt.compare(password, hashedPassword); } catch (error) { throw new Error('Password comparison failed'); } }; module.exports = { hashPassword, comparePassword }; // generateToken.js const jwt = require('jsonwebtoken'); const generateToken = (userId) => { if (!process.env.JWT_SECRET) { throw new Error('JWT_SECRET environment variable is not set'); } return jwt.sign( { id: userId }, process.env.JWT_SECRET, { expiresIn: '7d' } ); }; module.exports = generateToken; // authController.js const User = require('../models/User'); const { hashPassword, comparePassword } = require('../utils/hashPassword'); const generateToken = require('../utils/generateToken'); const register = async (req, res) => { try { const { email, password } = req.body; if (!email || !password) { return res.status(400).json({ error: 'Email and password are required' }); } const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(409).json({ error: 'An account with this email already exists' }); } const hashedPassword = await hashPassword(password); const user = await User.create({ email, password: hashedPassword }); const token = generateToken(user._id); res.status(201).json({ message: 'Account created successfully', token, user: { id: user._id, email: user.email } }); } catch (error) { res.status(500).json({ error: 'Registration failed. Please try again.' }); } }; const login = async (req, res) => { try { const { email, password } = req.body; if (!email || !password) { return res.status(400).json({ error: 'Email and password are required' }); } const user = await User.findOne({ email }); if (!user) { return res.status(401).json({ error: 'Invalid email or password' }); } const isMatch = await comparePassword(password, user.password); if (!isMatch) { return res.status(401).json({ error: 'Invalid email or password' }); } const token = generateToken(user._id); res.status(200).json({ message: 'Login successful', token, user: { id: user._id, email: user.email } }); } catch (error) { res.status(500).json({ error: 'Login failed. Please try again.' }); } }; module.exports = { register, login }; // authMiddleware.js const jwt = require('jsonwebtoken'); const User = require('../models/User'); const protect = async (req, res, next) => { try { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ error: 'Not authorised. No token provided.' }); } const token = authHeader.split(' ')[1]; const decoded = jwt.verify(token, process.env.JWT_SECRET); const user = await User.findById(decoded.id).select('-password'); if (!user) { return res.status(401).json({ error: 'Not authorised. User no longer exists.' }); } req.user = user; next(); } catch (error) { res.status(401).json({ error: 'Not authorised. Token is invalid or expired.' }); } }; module.exports = protect; // authRoutes.js const express = require('express'); const router = express.Router(); const { register, login } = require('../authController'); router.post('/register', register); router.post('/login', login); module.exports = router; EDGE CASES HANDLED 1. Duplicate email registration: Returns 409 error before attempting to create user, preventing database errors and exposing whether an email exists. 2. Missing request body fields: Validates email and password presence before any database operation, returning a clear 400 error. 3. Expired or invalid JWT: Middleware catches jwt.verify errors and returns 401, preventing access to protected routes with stale tokens. SECURITY NOTES - Passwords hashed with bcrypt at salt round 12 — brute force resistant and never stored in plaintext - JWT errors and user-not-found errors return identical messages — prevents account enumeration attacks - JWT_SECRET validated at token generation — prevents silent failures if environment variable is missing HOW TO IMPLEMENT 1. Run: npm install mongoose bcryptjs jsonwebtoken express 2. Create a .env file and add JWT_SECRET=your_long_random_secret_here and your MongoDB connection string 3. Copy all files into the folder structure shown above 4. In your main app.js, add: app.use('/api/auth', require('./src/auth/authRoutes')) 5. Connect mongoose: mongoose.connect(process.env.MONGO_URI) in your app entry point 6. Test registration by sending POST to /api/auth/register with { email, password } in the request body 7. Test login by sending POST to /api/auth/login with the same credentials TESTING CHECKLIST 1. POST /api/auth/register with valid email and password — expect 201 response with token and user object 2. POST /api/auth/register with the same email again — expect 409 error with duplicate account message 3. POST /api/auth/login with correct credentials — expect 200 response with valid JWT token 4. POST /api/auth/login with wrong password — expect 401 error with generic invalid credentials message 5. Send request to a protected route with expired token — expect 401 error with token invalid message
🌀 Claude

Full Stack Feature Builders For

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
CLAUDE-4-7-OPUS
Tested icon
Guide icon
4 examples icon
Free credits icon
Build any app feature from scratch — get working code, file structure, error handling, edge cases and documentation in one run. Input your feature, tech stack, user type and output format — Claude writes production-ready code with full explanation instantly. Built for solo developers, freelancers, non-technical founders and agencies. Optimised for Claude Sonnet and Opus.
...more
Added 6 days ago
Report
Browse Marketplace