Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- โ Backend: Node.js + Express (Twilio OTP Server)
- npm install express cors dotenv twilio
- .env
- PORT=5000
- TWILIO_SID=your_twilio_sid
- TWILIO_AUTH_TOKEN=your_twilio_auth_token
- TWILIO_PHONE=+1234567890
- ๐ twilioClient.js
- import twilio from 'twilio';
- import dotenv from 'dotenv';
- dotenv.config();
- const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
- export default client;
- ๐ routes/otp.js
- import express from 'express';
- import client from '../twilioClient.js';
- const router = express.Router();
- const otpStore = {};
- router.post('/send', async (req, res) => {
- const { phone } = req.body;
- const code = Math.floor(100000 + Math.random() * 900000).toString();
- otpStore[phone] = { code, expires: Date.now() + 300000 };
- await client.messages.create({
- body: `Your OTP is: ${code}`,
- from: process.env.TWILIO_PHONE,
- to: phone,
- });
- res.json({ message: 'OTP sent' });
- });
- router.post('/verify', (req, res) => {
- const { phone, code } = req.body;
- const record = otpStore[phone];
- if (!record || Date.now() > record.expires) {
- return res.status(400).json({ success: false, message: 'OTP expired or invalid' });
- }
- if (record.code !== code) {
- return res.status(400).json({ success: false, message: 'Invalid OTP' });
- }
- delete otpStore[phone];
- res.json({ success: true, message: 'OTP verified' });
- });
- export default router;
- ๐ server.js
- import express from 'express';
- import dotenv from 'dotenv';
- import cors from 'cors';
- import otpRoutes from './routes/otp.js';
- dotenv.config();
- const app = express();
- app.use(cors());
- app.use(express.json());
- app.use('/api/otp', otpRoutes);
- app.listen(process.env.PORT, () => {
- console.log(`Server running on port ${process.env.PORT}`);
- });
- ๐ป Frontend: React (Vite)
- ๐ฆ Install Vite + Axios
- npm create vite@latest frontend --template react
- cd frontend
- npm install axios
- ๐ OtpForm.jsx
- import { useState } from 'react';
- import axios from 'axios';
- const API = 'http://localhost:5000/api/otp';
- export default function OtpForm() {
- const [phone, setPhone] = useState('');
- const [code, setCode] = useState('');
- const [stage, setStage] = useState('input');
- const sendOTP = async () => {
- await axios.post(`${API}/send`, { phone });
- setStage('verify');
- };
- const verifyOTP = async () => {
- const res = await axios.post(`${API}/verify`, { phone, code });
- alert(res.data.message);
- };
- return (
- <div className="max-w-md mx-auto mt-20 p-4 border rounded">
- <h2 className="text-xl mb-4 font-bold">Phone OTP Login</h2>
- {stage === 'input' ? (
- <>
- <input
- type="text"
- placeholder="Enter phone number"
- value={phone}
- onChange={(e) => setPhone(e.target.value)}
- className="border p-2 w-full mb-3"
- />
- <button onClick={sendOTP} className="bg-blue-500 text-white px-4 py-2 rounded">
- Send OTP
- </button>
- </>
- ) : (
- <>
- <input
- type="text"
- placeholder="Enter OTP"
- value={code}
- onChange={(e) => setCode(e.target.value)}
- className="border p-2 w-full mb-3"
- />
- <button onClick={verifyOTP} className="bg-green-500 text-white px-4 py-2 rounded">
- Verify
- </button>
- </>
- )}
- </div>
- );
- }
- ๐ App.jsx
- import OtpForm from './components/OtpForm';
- function App() {
- return <OtpForm />;
- }
- export default App;
- ๐งช Test the Flow
- Start your backend: node server.js
- Start frontend: npm run dev
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement