API Reference
API Code Examples
This page provides practical code examples for integrating with the Waitlister API in different programming languages and frameworks. These examples can help you quickly get started with implementing Waitlister in your projects.
JavaScript / Node.js
Integration Example (Node.js)
This example shows how to create a simple Express server that handles waitlist sign-ups and forwards them to the Waitlister API.
const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');
const app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
// Configuration
const config = {
waitlistKey: 'your-waitlist-key',
apiKey: 'your-api-key'
};
// Serve a simple HTML form
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// Handle sign-up form submission
app.post('/api/sign-up', async (req, res) => {
try {
const { email, name } = req.body;
// Validate input
if (!email) {
return res.status(400).json({ success: false, message: 'Email is required' });
}
// Forward request to Waitlister API
const response = await fetch(`https://waitlister.me/api/v1/waitlist/${config.waitlistKey}/sign-up`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': config.apiKey
},
body: JSON.stringify({
email,
name,
metadata: {
referring_domain: req.get('Referrer') || 'direct'
}
})
});
const data = await response.json();
if (!response.ok) {
return res.status(response.status).json(data);
}
return res.json(data);
} catch (error) {
console.error('Error adding subscriber:', error);
return res.status(500).json({ success: false, message: 'Server error' });
}
});
// Log views
app.post('/api/log-view', async (req, res) => {
try {
const { visitorId } = req.body;
// Forward request to Waitlister API
const response = await fetch(`https://waitlister.me/api/v1/waitlist/${config.waitlistKey}/log-view`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Api-Key': config.apiKey
},
body: JSON.stringify({
visitor_id: visitorId,
metadata: {
referring_domain: req.get('Referrer') || 'direct'
}
})
});
const data = await response.json();
if (!response.ok) {
return res.status(response.status).json(data);
}
return res.json(data);
} catch (error) {
console.error('Error logging view:', error);
return res.status(500).json({ success: false, message: 'Server error' });
}
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Frontend Implementation
This example shows a simple HTML form and JavaScript that works with the above server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Join Our Waitlist</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.thank-you {
display: none;
background-color: #f8f9fa;
padding: 20px;
border-radius: 4px;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Join Our Waitlist</h1>
<div id="sign-up-form">
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" id="email" required>
</div>
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" id="name">
</div>
<button id="submit-btn">Join Waitlist</button>
</div>
<div id="thank-you" class="thank-you">
<h2>Thank You!</h2>
<p>You're #<span id="position"></span> in line.</p>
<p>Share your unique referral link to move up the waitlist:</p>
<input type="text" id="referral-link" readonly>
</div>
<script>
// Generate or retrieve visitor ID
function getVisitorId() {
let visitorId = localStorage.getItem('waitlist_visitor_id');
if (!visitorId) {
visitorId = 'visitor-' + Math.random().toString(36).substring(2, 15);
localStorage.setItem('waitlist_visitor_id', visitorId);
}
return visitorId;
}
// Log view when page loads
document.addEventListener('DOMContentLoaded', async () => {
const visitorId = getVisitorId();
try {
await fetch('/api/log-view', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ visitorId })
});
} catch (error) {
console.error('Error logging view:', error);
}
});
// Handle form submission
document.getElementById('submit-btn').addEventListener('click', async () => {
const email = document.getElementById('email').value;
const name = document.getElementById('name').value;
if (!email) {
alert('Please enter your email address.');
return;
}
try {
const response = await fetch('/api/sign-up', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, name })
});
const data = await response.json();
if (!response.ok) {
alert(`Error: ${data.error?.message || 'Something went wrong'}`);
return;
}
// Show thank you message
document.getElementById('sign-up-form').style.display = 'none';
document.getElementById('thank-you').style.display = 'block';
document.getElementById('position').textContent = data.position;
// Create referral link
const referralLink = `${window.location.origin}?ref=${data.referral_code}`;
document.getElementById('referral-link').value = referralLink;
} catch (error) {
console.error('Error signing up:', error);
alert('An error occurred. Please try again later.');
}
});
</script>
</body>
</html>
React Implementation
Here's an example of a React component that integrates with the Waitlister API.
import React, { useState, useEffect } from 'react';
const WaitlistForm = () => {
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false);
const [error, setError] = useState('');
const [position, setPosition] = useState(null);
const [referralCode, setReferralCode] = useState('');
// Log view when component mounts
useEffect(() => {
const logView = async () => {
// Get or generate visitor ID
let visitorId = localStorage.getItem('waitlist_visitor_id');
if (!visitorId) {
visitorId = 'visitor-' + Math.random().toString(36).substring(2, 15);
localStorage.setItem('waitlist_visitor_id', visitorId);
}
try {
await fetch('/api/log-view', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ visitorId })
});
} catch (error) {
console.error('Error logging view:', error);
}
};
logView();
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
if (!email) {
setError('Email is required');
return;
}
setLoading(true);
setError('');
try {
const response = await fetch('/api/sign-up', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, name })
});
const data = await response.json();
if (!response.ok) {
setError(data.error?.message || 'Something went wrong');
setLoading(false);
return;
}
setPosition(data.position);
setReferralCode(data.referral_code);
setSuccess(true);
setLoading(false);
} catch (error) {
console.error('Error signing up:', error);
setError('An error occurred. Please try again later.');
setLoading(false);
}
};
if (success) {
const referralLink = `${window.location.origin}?ref=${referralCode}`;
return (
<div className="thank-you-container">
<h2>Thank You!</h2>
<p>You're #{position} in line.</p>
<p>Share your unique referral link to move up the waitlist:</p>
<input
type="text"
value={referralLink}
readOnly
onClick={(e) => e.target.select()}
/>
</div>
);
}
return (
<form onSubmit={handleSubmit}>
<h2>Join Our Waitlist</h2>
{error && <div className="error">{error}</div>}
<div className="form-group">
<label htmlFor="email">Email Address</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="form-group">
<label htmlFor="name">Your Name</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<button type="submit" disabled={loading}>
{loading ? 'Submitting...' : 'Join Waitlist'}
</button>
</form>
);
};
export default WaitlistForm;
PHP Example
Here's how to integrate with the Waitlister API using PHP.
<?php
// Configuration
$waitlistKey = 'your-waitlist-key';
$apiKey = 'your-api-key';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get form data
$email = $_POST['email'] ?? '';
$name = $_POST['name'] ?? '';
// Validate input
if (empty($email)) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Email is required']);
exit;
}
// Prepare request data
$data = [
'email' => $email,
'name' => $name,
'metadata' => [
'referring_domain' => $_SERVER['HTTP_REFERER'] ?? 'direct'
]
];
// Add subscriber to waitlist
$result = addSubscriber($waitlistKey, $apiKey, $data);
// Return result as JSON
header('Content-Type: application/json');
echo json_encode($result);
exit;
}
/**
* Add a subscriber to the waitlist
*
* @param string $waitlistKey The waitlist key
* @param string $apiKey The API key
* @param array $data The subscriber data
* @return array The API response
*/
function addSubscriber($waitlistKey, $apiKey, $data) {
$url = "https://waitlister.me/api/v1/waitlist/{$waitlistKey}/sign-up";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"X-Api-Key: {$apiKey}"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return json_decode($response, true);
}
/**
* Log a waitlist view
*
* @param string $waitlistKey The waitlist key
* @param string $apiKey The API key
* @param string $visitorId Unique visitor ID
* @return array The API response
*/
function logView($waitlistKey, $apiKey, $visitorId) {
$url = "https://waitlister.me/api/v1/waitlist/{$waitlistKey}/log-view";
$data = [
'visitor_id' => $visitorId,
'metadata' => [
'referring_domain' => $_SERVER['HTTP_REFERER'] ?? 'direct'
]
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"X-Api-Key: {$apiKey}"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return json_decode($response, true);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Join Our Waitlist</title>
<style>
/* CSS styles here */
</style>
</head>
<body>
<h1>Join Our Waitlist</h1>
<div id="sign-up-form">
<form method="post" id="waitlist-form">
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" id="name" name="name">
</div>
<button type="submit">Join Waitlist</button>
</form>
</div>
<div id="thank-you" class="thank-you" style="display: none;">
<h2>Thank You!</h2>
<p>You're #<span id="position"></span> in line.</p>
<p>Share your unique referral link to move up the waitlist:</p>
<input type="text" id="referral-link" readonly>
</div>
<script>
// JavaScript to handle form submission and display thank you message
document.getElementById('waitlist-form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
fetch(window.location.href, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById('sign-up-form').style.display = 'none';
document.getElementById('thank-you').style.display = 'block';
document.getElementById('position').textContent = data.position;
const referralLink = `${window.location.origin}?ref=${data.referral_code}`;
document.getElementById('referral-link').value = referralLink;
} else {
alert(data.message || 'An error occurred. Please try again.');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred. Please try again later.');
});
});
// Log view on page load
document.addEventListener('DOMContentLoaded', function() {
// Get or create visitor ID from/in localStorage
let visitorId = localStorage.getItem('waitlist_visitor_id');
if (!visitorId) {
visitorId = 'visitor-' + Math.random().toString(36).substring(2, 15);
localStorage.setItem('waitlist_visitor_id', visitorId);
}
// This would need a separate PHP endpoint for logging views
// For simplicity, we're not implementing that here
});
</script>
</body>
</html>
Best Practices
When implementing the Waitlister API, follow these best practices.
- Keep your API key secure
- Never expose your API key in client-side code
- Use server-side code to make API requests
- Store your API key as an environment variable
- Implement proper error handling
- Check for and handle error responses from the API
- Provide clear feedback to users when errors occur
- Log errors for troubleshooting
- Generate unique visitor IDs
- Use a consistent method to generate visitor IDs
- Store IDs in localStorage or cookies for returning visitors
- Send visitor IDs with log-view requests to prevent duplicate counts
- Track referrals properly
- Extract referral codes from URL parameters
- Include referral codes in sign-up requests
- Provide users with their referral links after sign-up
- Consider rate limits
- Implement exponential backoff for retries
- Queue requests if you expect high volume
- Monitor your API usage to stay within limits
Next Steps
Now that you've seen examples of how to integrate with the Waitlister API, you might want to:
- Review the Add Subscriber endpoint documentation
- Learn about API rate limits and how to handle them
- Implement proper authentication in your application