Advertisement
xerocool-101

012 (Twilio OTP Server)

Apr 21st, 2025
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 3.65 KB | Software | 0 0
  1. โœ… Backend: Node.js + Express (Twilio OTP Server)
  2. npm install express cors dotenv twilio
  3.  
  4. .env
  5. PORT=5000
  6. TWILIO_SID=your_twilio_sid
  7. TWILIO_AUTH_TOKEN=your_twilio_auth_token
  8. TWILIO_PHONE=+1234567890
  9.  
  10. ๐Ÿ“„ twilioClient.js
  11. import twilio from 'twilio';
  12. import dotenv from 'dotenv';
  13. dotenv.config();
  14.  
  15. const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
  16. export default client;
  17.  
  18. ๐Ÿ“„ routes/otp.js
  19. import express from 'express';
  20. import client from '../twilioClient.js';
  21.  
  22. const router = express.Router();
  23. const otpStore = {};
  24.  
  25. router.post('/send', async (req, res) => {
  26.   const { phone } = req.body;
  27.   const code = Math.floor(100000 + Math.random() * 900000).toString();
  28.   otpStore[phone] = { code, expires: Date.now() + 300000 };
  29.  
  30.   await client.messages.create({
  31.     body: `Your OTP is: ${code}`,
  32.     from: process.env.TWILIO_PHONE,
  33.     to: phone,
  34.   });
  35.  
  36.   res.json({ message: 'OTP sent' });
  37. });
  38.  
  39. router.post('/verify', (req, res) => {
  40.   const { phone, code } = req.body;
  41.   const record = otpStore[phone];
  42.  
  43.   if (!record || Date.now() > record.expires) {
  44.     return res.status(400).json({ success: false, message: 'OTP expired or invalid' });
  45.   }
  46.  
  47.   if (record.code !== code) {
  48.     return res.status(400).json({ success: false, message: 'Invalid OTP' });
  49.   }
  50.  
  51.   delete otpStore[phone];
  52.   res.json({ success: true, message: 'OTP verified' });
  53. });
  54.  
  55. export default router;
  56.  
  57. ๐Ÿ“„ server.js
  58. import express from 'express';
  59. import dotenv from 'dotenv';
  60. import cors from 'cors';
  61. import otpRoutes from './routes/otp.js';
  62.  
  63. dotenv.config();
  64.  
  65. const app = express();
  66. app.use(cors());
  67. app.use(express.json());
  68.  
  69. app.use('/api/otp', otpRoutes);
  70.  
  71. app.listen(process.env.PORT, () => {
  72.   console.log(`Server running on port ${process.env.PORT}`);
  73. });
  74.  
  75. ๐Ÿ’ป Frontend: React (Vite)
  76. ๐Ÿ“ฆ Install Vite + Axios
  77. npm create vite@latest frontend --template react
  78. cd frontend
  79. npm install axios
  80.  
  81. ๐Ÿ“„ OtpForm.jsx
  82. import { useState } from 'react';
  83. import axios from 'axios';
  84.  
  85. const API = 'http://localhost:5000/api/otp';
  86.  
  87. export default function OtpForm() {
  88.   const [phone, setPhone] = useState('');
  89.   const [code, setCode] = useState('');
  90.   const [stage, setStage] = useState('input');
  91.  
  92.   const sendOTP = async () => {
  93.     await axios.post(`${API}/send`, { phone });
  94.     setStage('verify');
  95.   };
  96.  
  97.   const verifyOTP = async () => {
  98.     const res = await axios.post(`${API}/verify`, { phone, code });
  99.     alert(res.data.message);
  100.   };
  101.  
  102.   return (
  103.     <div className="max-w-md mx-auto mt-20 p-4 border rounded">
  104.       <h2 className="text-xl mb-4 font-bold">Phone OTP Login</h2>
  105.  
  106.       {stage === 'input' ? (
  107.         <>
  108.           <input
  109.             type="text"
  110.             placeholder="Enter phone number"
  111.             value={phone}
  112.             onChange={(e) => setPhone(e.target.value)}
  113.             className="border p-2 w-full mb-3"
  114.           />
  115.           <button onClick={sendOTP} className="bg-blue-500 text-white px-4 py-2 rounded">
  116.             Send OTP
  117.           </button>
  118.         </>
  119.       ) : (
  120.         <>
  121.           <input
  122.             type="text"
  123.             placeholder="Enter OTP"
  124.             value={code}
  125.             onChange={(e) => setCode(e.target.value)}
  126.             className="border p-2 w-full mb-3"
  127.           />
  128.           <button onClick={verifyOTP} className="bg-green-500 text-white px-4 py-2 rounded">
  129.             Verify
  130.           </button>
  131.         </>
  132.       )}
  133.     </div>
  134.   );
  135. }
  136.  
  137. ๐Ÿ“„ App.jsx
  138. import OtpForm from './components/OtpForm';
  139.  
  140. function App() {
  141.   return <OtpForm />;
  142. }
  143.  
  144. export default App;
  145.  
  146. ๐Ÿงช Test the Flow
  147. Start your backend: node server.js
  148. Start frontend: npm run dev
  149.  
Tags: JavaScript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement