-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
75 lines (63 loc) · 2.07 KB
/
server.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const express = require('express');
const next = require('next');
const fetch = require('node-fetch');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
// Function to handle rendering for both subdomain and /site/:slug
const renderSite = async (slug, res) => {
const baseUrl = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/shipstation-websites/websites`;
const url = `${baseUrl}/${slug}/index.html`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Failed to fetch HTML');
}
const htmlContent = await response.text();
res.setHeader('Content-Type', 'text/html');
res.send(htmlContent);
} catch (error) {
console.error('Error:', error);
res.redirect(process.env.NEXT_PUBLIC_MAIN_URL);
}
};
// Handle /site/:slug route
server.get('/site/:slug', async (req, res) => {
const { slug } = req.params;
await renderSite(slug, res);
});
// Handle NEXT_PUBLIC_PROFILE_DOMAIN/slug route
server.get('/:slug', async (req, res, next) => {
const { slug } = req.params;
const hostname = req.hostname;
const mainDomain = process.env.NEXT_PUBLIC_PROFILE_DOMAIN;
if (hostname === mainDomain) {
await renderSite(slug, res);
} else {
next();
}
});
// Handle subdomain routing
server.use((req, res, next) => {
const hostname = req.hostname;
const mainDomain = process.env.NEXT_PUBLIC_PROFILE_DOMAIN;
console.log("Got request for", hostname);
if (hostname !== mainDomain && hostname.endsWith(`.${mainDomain}`)) {
const slug = hostname.replace(`.${mainDomain}`, '');
console.log("Rendering", slug);
renderSite(slug, res);
} else {
next();
}
});
server.all('*', (req, res) => {
return handle(req, res);
});
const port = process.env.PORT || 3000;
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on ${port}`);
});
});