Next.js Integration
Build SMS applications with Next.js and sms-dev for local testing and development.
Quick Setup
Get started with Next.js and sms-dev in under 5 minutes.
1. Install Dependencies
# Initialize a Next.js app npx create-next-app sms-next-app cd sms-next-app # Install sms-dev globally npm install -g @relay/sms-dev # Start sms-dev in the background sms-dev
2. Basic API Route
Create a simple API route for sending SMS
// pages/api/send-sms.js
export default async (req, res) => {
if (req.method === 'POST') {
const { to, from, body } = req.body;
if (!to || !from || !body) {
return res.status(400).json({
error: 'Missing required fields: to, from, body'
});
}
try {
const response = await fetch('http://localhost:4001/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ to, from, body })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
res.json({
success: true,
messageId: result.id,
message: 'SMS sent successfully'
});
} catch (error) {
res.status(500).json({
error: 'Failed to send SMS',
details: error.message
});
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
};3. Webhook Handler
Handle incoming SMS messages from the Virtual Phone
// pages/api/webhook.js
export default async function handler(req, res) {
if (req.method === 'POST') {
const { from, to, body, messageId } = req.body;
console.log(`Received SMS from ${from}: ${body}`);
// Process the incoming message
await handleIncomingMessage(from, to, body);
res.status(200).json({ success: true });
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
async function handleIncomingMessage(from, to, body) {
const message = body.toLowerCase().trim();
if (message === 'help') {
// Send help response
await fetch('http://localhost:4001/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
to: from,
from: to,
body: 'Available commands: HELP, TIME, INFO'
})
});
} else if (message === 'time') {
const now = new Date().toLocaleString();
await fetch('http://localhost:4001/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
to: from,
from: to,
body: `Current time: ${now}`
})
});
}
}Running the Example
Step-by-Step Instructions
1
Start sms-dev
Run sms-dev --webhook-url http://localhost:3000/api/webhook
2
Start your Next.js server
Run npm run dev
3
Send a test SMS
POST to http://localhost:3000/api/send-sms
Test Request Example
Use curl or Postman to test your SMS endpoint
# Send an SMS message
curl -X POST http://localhost:3000/api/send-sms \
-H "Content-Type: application/json" \
-d '{
"to": "+1234567890",
"from": "+1987654321",
"body": "Hello from Next.js! Reply HELP for commands."
}'
# Response:
{
"success": true,
"messageId": "msg_abc123",
"message": "SMS sent successfully"
}