-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
212 lines (187 loc) · 8.36 KB
/
Copy pathserver.js
File metadata and controls
212 lines (187 loc) · 8.36 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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { readFileSync } from 'fs';
import dotenv from 'dotenv';
import {
SEO_ROUTE_TYPES,
resolveApiBaseUrl,
resolveSeoServerApiBaseUrl,
fetchSeoMetadata,
fetchText,
getFallbackMetadata,
injectMetaTags,
buildRobotsTxt,
} from './seo/seo-core.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Always load .env from the app directory (PM2 cwd may differ)
dotenv.config({ path: join(__dirname, '.env') });
const app = express();
// PORT for the SEO server (prefer PORT, fall back to VITE_PORT, then 3000)
const PORT = process.env.PORT
? parseInt(process.env.PORT, 10)
: (process.env.VITE_PORT ? parseInt(process.env.VITE_PORT, 10) : 3000);
if (process.env.PORT) {
console.log(`[SEO Server] Using PORT from .env: ${PORT}`);
} else if (process.env.VITE_PORT) {
console.log(`[SEO Server] Using VITE_PORT from .env: ${PORT} (consider setting PORT explicitly)`);
} else {
console.warn(`[SEO Server] ⚠ No PORT found in .env, using default: ${PORT}`);
}
const DEFAULT_API_BASE_URL = resolveSeoServerApiBaseUrl(process.env);
// Check dist (important for preview/production)
const distPath = join(__dirname, 'dist');
const distIndexPath = join(distPath, 'index.html');
try {
readFileSync(distIndexPath, 'utf-8');
console.log(`[SEO Server] ✓ Found dist directory at: ${distPath}`);
} catch {
if (process.env.NODE_ENV === 'production') {
console.warn(`[SEO Server] ⚠ dist/index.html not found — run 'npm run build' first`);
} else {
console.log(`[SEO Server] ℹ Development mode: dist will be created on first build`);
}
}
// Trust proxy for proper protocol detection
app.set('trust proxy', true);
const SITE_NAME = process.env.SITE_NAME || process.env.VITE_SITE_NAME || 'DevCommunity';
/** Public site hostname — prefer proxy headers over internal bind address. */
function getPublicHost(req) {
const forwarded = req.get('x-forwarded-host');
if (forwarded) return forwarded.split(',')[0].trim();
return req.get('host') || '';
}
/** Base URL of the public site, from the incoming request. */
function getBaseUrl(req) {
const host = getPublicHost(req) || `localhost:${PORT}`;
const protocol =
req.get('x-forwarded-proto') ||
req.protocol ||
(req.secure ? 'https' : 'http');
return `${protocol}://${host}`;
}
/** Headers forwarded to the API so it builds URLs with the public host. */
function apiForwardHeaders(req) {
const host = getPublicHost(req);
const proto =
req.get('x-forwarded-proto') ||
req.protocol ||
(req.secure ? 'https' : 'http');
if (!host) return {};
return {
'x-forwarded-host': host,
'x-forwarded-proto': proto,
};
}
function readDistIndex() {
return readFileSync(join(__dirname, 'dist', 'index.html'), 'utf-8');
}
/** Redirect to the Vite dev server when dist isn't built yet (dev only). */
function redirectToViteIfDev(req, res) {
if (process.env.NODE_ENV !== 'production') {
const vitePort = process.env.VITE_PORT || 5173;
res.redirect(`http://localhost:${vitePort}${req.originalUrl}`);
return true;
}
res.status(503).send('Application is building. Please try again in a moment.');
return true;
}
// ---------------------------------------------------------------------------
// SEO route handler (injects per-resource meta into the SPA shell)
// ---------------------------------------------------------------------------
async function handleSeoRoute(req, res, type) {
const identifier = req.params.slug || req.params.id;
let html;
try {
html = readDistIndex();
} catch {
return redirectToViteIfDev(req, res);
}
try {
const publicHost = getPublicHost(req);
const apiBaseUrl = resolveSeoServerApiBaseUrl(process.env, publicHost) || DEFAULT_API_BASE_URL;
const fwdHeaders = apiForwardHeaders(req);
const { data: metadata, apiBase: usedApiBase } = await fetchSeoMetadata({
apiBaseUrl,
type,
identifier,
headers: fwdHeaders,
env: process.env,
host: publicHost,
});
const ctx = { baseUrl: getBaseUrl(req), currentPath: req.originalUrl || req.url || '', host: publicHost };
const usingFallback = !metadata;
html = injectMetaTags(
html,
metadata || getFallbackMetadata({ baseUrl: ctx.baseUrl, siteName: SITE_NAME, currentPath: ctx.currentPath }),
ctx
);
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', usingFallback ? 'public, max-age=300' : 'public, max-age=3600, s-maxage=3600');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-SEO-Status', usingFallback ? 'fallback' : 'ok');
res.setHeader('X-SEO-API', usedApiBase || apiBaseUrl);
if (usingFallback) {
console.warn(`[SEO Server] fallback for ${type}/${identifier} tried ${usedApiBase || apiBaseUrl} host=${publicHost || '(none)'}`);
}
return res.send(html);
} catch {
const ctx = { baseUrl: getBaseUrl(req), currentPath: req.originalUrl || '', host: getPublicHost(req) };
const fallback = getFallbackMetadata({ baseUrl: ctx.baseUrl, siteName: SITE_NAME, currentPath: ctx.currentPath });
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=300');
return res.send(injectMetaTags(html, fallback, ctx));
}
}
// ---------------------------------------------------------------------------
// AI / crawler discovery artefacts (must precede static + catch-all)
// ---------------------------------------------------------------------------
app.get('/robots.txt', (req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.send(buildRobotsTxt({ baseUrl: getBaseUrl(req) }));
});
app.get('/sitemap.xml', async (req, res) => {
const apiBaseUrl = resolveSeoServerApiBaseUrl(process.env, getPublicHost(req)) || DEFAULT_API_BASE_URL;
const xml = await fetchText({ url: `${apiBaseUrl}/seo/sitemap.xml`, headers: apiForwardHeaders(req) });
res.setHeader('Content-Type', 'application/xml; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=3600, s-maxage=3600');
if (!xml) {
return res.status(502).send('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>');
}
return res.send(xml);
});
app.get('/llms.txt', async (req, res) => {
const apiBaseUrl = resolveSeoServerApiBaseUrl(process.env, getPublicHost(req)) || DEFAULT_API_BASE_URL;
const txt = await fetchText({ url: `${apiBaseUrl}/seo/llms.txt`, headers: apiForwardHeaders(req) });
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'public, max-age=3600, s-maxage=3600');
return res.send(txt || `# ${SITE_NAME}\n\n> Where developers build the future.\n`);
});
// ---------------------------------------------------------------------------
// SEO routes (with and without trailing slash)
// ---------------------------------------------------------------------------
for (const [prefix, type] of Object.entries(SEO_ROUTE_TYPES)) {
app.get(`/${prefix}/:slug`, (req, res) => handleSeoRoute(req, res, type));
app.get(`/${prefix}/:slug/`, (req, res) => handleSeoRoute(req, res, type));
}
// Static assets AFTER SEO routes so SEO routes win
app.use(express.static(join(__dirname, 'dist')));
// SPA catch-all
app.get('*', (req, res) => {
try {
readDistIndex();
} catch {
return redirectToViteIfDev(req, res);
}
res.sendFile(join(__dirname, 'dist', 'index.html'));
});
app.listen(PORT, () => {
console.log(`[SEO Server] ✓ Started on port ${PORT}`);
console.log(`[SEO Server] API base: ${DEFAULT_API_BASE_URL}`);
console.log(`[SEO Server] Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`[SEO Server] App URL: ${process.env.VITE_APP_URL || '(not set)'}`);
console.log(`[SEO Server] Internal API: ${process.env.SEO_API_INTERNAL_URL || '(not set)'}`);
console.log(`[SEO Server] SEO routes: ${Object.keys(SEO_ROUTE_TYPES).join(', ')}`);
});