EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
update_subdomain_cnames.js
Go to the documentation of this file.
1// Script to update all subdomain CNAMEs to point to your Cloudflare Tunnel hostname
2require('dotenv').config();
3const axios = require('axios');
4const pool = require('../services/db');
5
6const CLOUDFLARE_BASE_URL = process.env.CLOUDFLARE_BASE_URL || 'https://api.cloudflare.com/client/v4';
7const CLOUDFLARE_ZONE_ID = process.env.CLOUDFLARE_ZONE_ID;
8const CLOUDFLARE_TOKEN = process.env.CLOUDFLARE_TOKEN;
9const ZONE_NAME = process.env.ZONE_NAME || 'everydaytech.au';
10const TUNNEL_HOSTNAME = '52106555-6961-4b4d-bb84-1026b4892bec.cfargotunnel.com';
11
12/**
13 *
14 */
15async function updateSubdomainCNAMEs() {
16 if (!CLOUDFLARE_ZONE_ID || !CLOUDFLARE_TOKEN) {
17 throw new Error('Cloudflare credentials not configured');
18 }
19
20 const tenants = await pool.query('SELECT subdomain FROM tenants WHERE status = $1', ['active']);
21 const headers = {
22 Authorization: `Bearer ${CLOUDFLARE_TOKEN}`,
23 'Content-Type': 'application/json'
24 };
25
26 for (const row of tenants.rows) {
27 const subdomain = row.subdomain;
28 const fqdn = `${subdomain}.${ZONE_NAME}`;
29 // Find existing DNS record
30 const listUrl = `${CLOUDFLARE_BASE_URL}/zones/${CLOUDFLARE_ZONE_ID}/dns_records?type=CNAME&name=${fqdn}`;
31 const res = await axios.get(listUrl, { headers });
32 if (res.data.result && res.data.result.length > 0) {
33 // Update existing record
34 const recordId = res.data.result[0].id;
35 const updateUrl = `${CLOUDFLARE_BASE_URL}/zones/${CLOUDFLARE_ZONE_ID}/dns_records/${recordId}`;
36 const payload = {
37 type: 'CNAME',
38 name: fqdn,
39 content: TUNNEL_HOSTNAME,
40 ttl: 120,
41 proxied: true
42 };
43 const updateRes = await axios.put(updateUrl, payload, { headers });
44 if (updateRes.data.success) {
45 console.log(`✅ Updated CNAME for ${fqdn} → ${TUNNEL_HOSTNAME}`);
46 } else {
47 console.error(`❌ Failed to update ${fqdn}:`, updateRes.data.errors);
48 }
49 } else {
50 // Create new record
51 const createUrl = `${CLOUDFLARE_BASE_URL}/zones/${CLOUDFLARE_ZONE_ID}/dns_records`;
52 const payload = {
53 type: 'CNAME',
54 name: fqdn,
55 content: TUNNEL_HOSTNAME,
56 ttl: 120,
57 proxied: true
58 };
59 const createRes = await axios.post(createUrl, payload, { headers });
60 if (createRes.data.success) {
61 console.log(`✅ Created CNAME for ${fqdn} → ${TUNNEL_HOSTNAME}`);
62 } else {
63 console.error(`❌ Failed to create ${fqdn}:`, createRes.data.errors);
64 }
65 }
66 }
67 process.exit(0);
68}
69
70updateSubdomainCNAMEs().catch(err => {
71 console.error('Error:', err.message);
72 process.exit(1);
73});