Connecting JavaScript (Native / Vanilla JS) with HosteDay
In this guide, you will learn how to connect any Vanilla JavaScript / HTML web application directly to your HosteDay App step by step—covering authentication, CRUD operations, Realtime WebSockets, and Web Push Notifications (FCM v1).
1. Configure Base Constants
In your JavaScript application, define your App's base URL and API protection token (X-Api-Token):
const BASE_URL = 'https://my-app.hosteday.com';
const API_TOKEN = 'YOUR_API_TOKEN';
function getHeaders(includeAuth = false) {
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Api-Token': API_TOKEN,
};
if (includeAuth) {
const userToken = localStorage.getItem('user_token');
if (userToken) {
headers['Authorization'] = `Bearer ${userToken}`;
}
}
return headers;
}
2. Authentication & Token Management
Sign In & Persist Token (POST /api/auth/login)
async function login(email, password) {
const response = await fetch(`${BASE_URL}/api/auth/login`, {
method: 'POST',
headers: getHeaders(false),
body: JSON.stringify({ email, password }),
});
const result = await response.json();
if (response.ok && result.data?.token) {
localStorage.setItem('user_token', result.data.token);
}
return result;
}
Registration & Fetching Current User
- To register: send
POST ${BASE_URL}/api/auth/registerwithname,email,password, andpassword_confirmation. - To fetch the authenticated user profile:
async function fetchCurrentUser() {
const response = await fetch(`${BASE_URL}/api/user`, {
headers: getHeaders(true),
});
return response.json();
}
3. Performing CRUD Operations with fetch()
// List records (GET)
async function getProducts(page = 1) {
const response = await fetch(`${BASE_URL}/api/products?page=${page}`, {
headers: getHeaders(false),
});
return response.json();
}
// Create a record (POST - requires X-Api-Token + Authorization Bearer)
async function createProduct(name, price) {
const response = await fetch(`${BASE_URL}/api/products`, {
method: 'POST',
headers: getHeaders(true),
body: JSON.stringify({ name, price }),
});
return response.json();
}
4. Receiving Live Updates (Realtime WebSockets)
Connect to the encrypted WebSocket endpoint at wss://ws1.hosteday.com/app/{REVERB_APP_KEY}:
const REVERB_APP_KEY = 'YOUR_REVERB_APP_KEY';
const ws = new WebSocket(`wss://ws1.hosteday.com/app/${REVERB_APP_KEY}?protocol=7&client=js&version=8.4.0`);
ws.addEventListener('message', async (event) => {
const msg = JSON.parse(event.data);
// Subscribe to a Public channel once connected
if (msg.event === 'pusher:connection_established') {
ws.send(JSON.stringify({
event: 'pusher:subscribe',
data: { channel: 'news.updates' },
}));
// For Private channels, obtain a signature from /api/broadcasting/auth-manual first
const socketData = JSON.parse(msg.data);
const authRes = await fetch(`${BASE_URL}/api/broadcasting/auth-manual`, {
method: 'POST',
headers: getHeaders(true),
body: JSON.stringify({
socket_id: socketData.socket_id,
channel_name: 'private-orders.42',
}),
});
const authJson = await authRes.json();
ws.send(JSON.stringify({
event: 'pusher:subscribe',
data: { channel: 'private-orders.42', auth: authJson.auth },
}));
}
});
5. Web Push Notifications (FCM v1)
After adding firebase-messaging-sw.js to your public/ directory, retrieve the browser FCM token and register it via POST /api/notifications/devices/register:
import { getMessaging, getToken } from 'firebase/messaging';
const messaging = getMessaging(firebaseApp);
const fcmToken = await getToken(messaging, { vapidKey: 'YOUR_VAPID_KEY' });
await fetch(`${BASE_URL}/api/notifications/devices/register`, {
method: 'POST',
headers: getHeaders(true),
body: JSON.stringify({
device_token: fcmToken,
device_id: browserDeviceId,
device_type: 'web',
device_name: navigator.userAgent,
}),
});