I'll help you create a mobile app backend with phone number authentication using OTP. Here's a complete setup with Node.js, Express, MongoDB, and Twilio for SMS.
Tech Stack Recommendation
- Node.js with Express.js
- MongoDB with Mongoose ODM
- Twilio for SMS OTP delivery
- JWT for authentication tokens
- Redis (optional) for OTP storage with TTL
Project Setup
First, initialize the project:
mkdir mobile-app-backend
cd mobile-app-backend
npm init -y
Install dependencies:
npm install express mongoose dotenv bcryptjs jsonwebtoken twilio express-validator cors helmet express-rate-limit
npm install -D nodemon
Project Structure
mobile-app-backend/
├── src/
│ ├── config/
│ │ ├── database.js
│ │ └── twilio.js
│ ├── models/
│ │ ├── User.js
│ │ └── OTP.js
│ ├── routes/
│ │ └── auth.js
│ ├── controllers/
│ │ └── authController.js
│ ├── middleware/
│ │ └── auth.js
│ └── utils/
│ └── generateOTP.js
├── .env
├── .gitignore
└── server.js
Implementation
1. Environment Variables (.env)
PORT=3000
MONGODB_URI=mongodb://localhost:27017/mobile-app
JWT_SECRET=your-secret-key-here
TWILIO_ACCOUNT_SID=your-twilio-account-sid
TWILIO_AUTH_TOKEN=your-twilio-auth-token
TWILIO_PHONE_NUMBER=+1234567890
OTP_EXPIRY_MINUTES=5
2. Database Configuration (src/config/database.js)
const mongoose = require('mongoose');
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('MongoDB connected successfully');
} catch (error) {
console.error('MongoDB connection error:', error);
process.exit(1);
}
};
module.exports = connectDB;
3. Twilio Configuration (src/config/twilio.js)
const twilio = require('twilio');
const client = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
module.exports = client;
4. User Model (src/models/User.js)
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
phoneNumber: {
type: String,
required: true,
unique: true,
match: /^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4,6}$/
},
countryCode: {
type: String,
required: true
},
isVerified: {
type: Boolean,
default: false
},
profile: {
name: {
type: String,
default: ''
},
email: {
type: String,
default: ''
},
avatar: {
type: String,
default: ''
}
},
createdAt: {
type: Date,
default: Date.now
},
lastLogin: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', userSchema);
5. OTP Model (src/models/OTP.js)
const mongoose = require('mongoose');
const otpSchema = new mongoose.Schema({
phoneNumber: {
type: String,
required: true
},
otp: {
type: String,
required: true
},
attempts: {
type: Number,
default: 0
},
createdAt: {
type: Date,
default: Date.now,
expires: 300 // OTP expires after 5 minutes
}
});
module.exports = mongoose.model('OTP', otpSchema);
6. OTP Generator Utility (src/utils/generateOTP.js)
const generateOTP = () => {
return Math.floor(100000 + Math.random() * 900000).toString();
};
module.exports = generateOTP;
7. Auth Controller (src/controllers/authController.js)
const User = require('../models/User');
const OTP = require('../models/OTP');
const jwt = require('jsonwebtoken');
const twilioClient = require('../config/twilio');
const generateOTP = require('../utils/generateOTP');
// Send OTP
exports.sendOTP = async (req, res) => {
try {
const { phoneNumber, countryCode } = req.body;
const fullPhoneNumber = `${countryCode}${phoneNumber}`;
// Generate OTP
const otpCode = generateOTP();
// Delete any existing OTP for this number
await OTP.deleteMany({ phoneNumber: fullPhoneNumber });
// Save OTP to database
const otpDoc = new OTP({
phoneNumber: fullPhoneNumber,
otp: otpCode
});
await otpDoc.save();
// Send OTP via Twilio
try {
await twilioClient.messages.create({
body: `Your verification code is: ${otpCode}. Valid for 5 minutes.`,
from: process.env.TWILIO_PHONE_NUMBER,
to: fullPhoneNumber
});
res.status(200).json({
success: true,
message: 'OTP sent successfully',
phoneNumber: fullPhoneNumber
});
} catch (twilioError) {
console.error('Twilio error:', twilioError);
// In development, you might want to return the OTP for testing
if (process.env.NODE_ENV === 'development') {
res.status(200).json({
success: true,
message: 'OTP generated (SMS failed in dev)',
phoneNumber: fullPhoneNumber,
otp: otpCode // Remove this in production!
});
} else {
throw new Error('Failed to send SMS');
}
}
} catch (error) {
console.error('Send OTP error:', error);
res.status(500).json({
success: false,
message: 'Failed to send OTP'
});
}
};
// Verify OTP and Login/Signup
exports.verifyOTP = async (req, res) => {
try {
const { phoneNumber, countryCode, otp } = req.body;
const fullPhoneNumber = `${countryCode}${phoneNumber}`;
// Find OTP document
const otpDoc = await OTP.findOne({
phoneNumber: fullPhoneNumber
}).sort({ createdAt: -1 });
if (!otpDoc) {
return res.status(400).json({
success: false,
message: 'OTP expired or not found'
});
}
// Check attempts
if (otpDoc.attempts >= 3) {
await OTP.deleteOne({ _id: otpDoc._id });
return res.status(400).json({
success: false,
message: 'Too many attempts. Please request new OTP'
});
}
// Verify OTP
if (otpDoc.otp !== otp) {
otpDoc.attempts += 1;
await otpDoc.save();
return res.status(400).json({
success: false,
message: 'Invalid OTP',
attemptsLeft: 3 - otpDoc.attempts
});
}
// OTP is valid, delete it
await OTP.deleteOne({ _id: otpDoc._id });
// Find or create user
let user = await User.findOne({ phoneNumber });
if (!user) {
// New user signup
user = new User({
phoneNumber,
countryCode,
isVerified: true
});
await user.save();
} else {
// Existing user login
user.isVerified = true;
user.lastLogin = new Date();
await user.save();
}
// Generate JWT token
const token = jwt.sign(
{ userId: user._id, phoneNumber: user.phoneNumber },
process.env.JWT_SECRET,
{ expiresIn: '30d' }
);
res.status(200).json({
success: true,
message: user.profile.name ? 'Login successful' : 'Signup successful',
token,
user: {
id: user._id,
phoneNumber: user.phoneNumber,
countryCode: user.countryCode,
profile: user.profile,
isNewUser: !user.profile.name
}
});
} catch (error) {
console.error('Verify OTP error:', error);
res.status(500).json({
success: false,
message: 'Failed to verify OTP'
});
}
};
// Resend OTP
exports.resendOTP = async (req, res) => {
try {
const { phoneNumber, countryCode } = req.body;
const fullPhoneNumber = `${countryCode}${phoneNumber}`;
// Check if OTP was recently sent
const recentOTP = await OTP.findOne({
phoneNumber: fullPhoneNumber,
createdAt: { $gt: new Date(Date.now() - 60000) } // 1 minute
});
if (recentOTP) {
return res.status(429).json({
success: false,
message: 'Please wait 1 minute before requesting new OTP'
});
}
// Send new OTP
await this.sendOTP(req, res);
} catch (error) {
console.error('Resend OTP error:', error);
res.status(500).json({
success: false,
message: 'Failed to resend OTP'
});
}
};
8. Auth Routes (src/routes/auth.js)
const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const authController = require('../controllers/authController');
// Validation middleware
const validate = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
success: false,
errors: errors.array()
});
}
next();
};
// Send OTP route
router.post('/send-otp', [
body('phoneNumber')
.notEmpty()
.matches(/^[0-9]{10}$/)
.withMessage('Invalid phone number format'),
body('countryCode')
.notEmpty()
.matches(/^[+][0-9]{1,4}$/)
.withMessage('Invalid country code')
], validate, authController.sendOTP);
// Verify OTP route
router.post('/verify-otp', [
body('phoneNumber')
.notEmpty()
.matches(/^[0-9]{10}$/)
.withMessage('Invalid phone number format'),
body('countryCode')
.notEmpty()
.matches(/^[+][0-9]{1,4}$/)
.withMessage('Invalid country code'),
body('otp')
.notEmpty()
.matches(/^[0-9]{6}$/)
.withMessage('Invalid OTP format')
], validate, authController.verifyOTP);
// Resend OTP route
router.post('/resend-otp', [
body('phoneNumber')
.notEmpty()
.matches(/^[0-9]{10}$/)
.withMessage('Invalid phone number format'),
body('countryCode')
.notEmpty()
.matches(/^[+][0-9]{1,4}$/)
.withMessage('Invalid country code')
], validate, authController.resendOTP);
module.exports = router;
9. Auth Middleware (src/middleware/auth.js)
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
throw new Error();
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.userId = decoded.userId;
req.phoneNumber = decoded.phoneNumber;
next();
} catch (error) {
res.status(401).json({
success: false,
message: 'Please authenticate'
});
}
};
10. Main Server File (server.js)
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const connectDB = require('./src/config/database');
const authRoutes = require('./src/routes/auth');
const app = express();
// Connect to MongoDB
connectDB();
// Security middleware
app.use(helmet());
app.use(cors());
app.use(express.json());
// Rate limiting for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 requests per window
message: 'Too many requests, please try again later'
});
// Routes
app.use('/api/auth', authLimiter, authRoutes);
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date() });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
success: false,
message: 'Something went wrong!'
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
11. Package.json Scripts
Update your package.json:
{
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
}
API Endpoints
-
Send OTP
- POST
/api/auth/send-otp
- Body:
{ "phoneNumber": "1234567890", "countryCode": "+91" }
-
Verify OTP
- POST
/api/auth/verify-otp
- Body:
{ "phoneNumber": "1234567890", "countryCode": "+91", "otp": "123456" }
-
Resend OTP
- POST
/api/auth/resend-otp
- Body:
{ "phoneNumber": "1234567890", "countryCode": "+91" }
Testing without Twilio
For testing without setting up Twilio, set NODE_ENV=development in your .env file. The OTP will be returned in the API response during development.
This setup provides a robust foundation for mobile authentication with proper security measures, rate limiting, and error handling. You can extend it by adding user profile management, refresh tokens, and other features as needed.