-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
42 lines (36 loc) · 1.26 KB
/
server.js
File metadata and controls
42 lines (36 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
require('dotenv').config();
const app = express();
// Validate environment variables
const { HASS_TOKEN, HASS_BASE_URL } = process.env;
if (!HASS_TOKEN || !HASS_BASE_URL) {
console.error('Missing required environment variables: HASS_TOKEN and HASS_BASE_URL must be set in .env');
process.exit(1);
}
app.use(express.json());
app.use('/', express.static('public'));
app.use('/webhook', createProxyMiddleware({
target: HASS_BASE_URL,
changeOrigin: true,
pathRewrite: { '^/webhook': '/api/webhook' },
logLevel: 'debug'
}));
app.use('/api', createProxyMiddleware({
target: HASS_BASE_URL,
changeOrigin: true,
pathRewrite: { '^/api': '/api' },
onProxyReq: (proxyReq, req) => {
proxyReq.setHeader('Authorization', `Bearer ${HASS_TOKEN}`);
if (req.method === 'POST' && req.body && Object.keys(req.body).length > 0) {
const bodyData = JSON.stringify(req.body);
proxyReq.setHeader('Content-Type', 'application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
proxyReq.writeData(bodyData);
}
},
logLevel: 'debug'
}));
app.listen(port=80, () => {
console.log('HA dashboard and proxy listening on port 80');
});