feat: Single-port deployment with improved error handling and SvelteKit static build
- Frontend now uses @sveltejs/adapter-static for production builds - Backend serves both API and static files from single port (originally port 3000) - Removed all throw statements from services to avoid Elysia prototype errors - Fixed favicon serving and SvelteKit assets path handling - Added ecosystem.config.js for PM2 process management - Comprehensive deployment documentation (PM2 + HAProxy) - Updated README with single-port architecture - Created start.sh script for easy production start
This commit is contained in:
@@ -28,7 +28,7 @@ import {
|
||||
|
||||
/**
|
||||
* Main backend application
|
||||
* Serves API routes
|
||||
* Serves API routes and static frontend files
|
||||
*/
|
||||
|
||||
// Get allowed origins from environment or allow all in development
|
||||
@@ -85,30 +85,30 @@ const app = new Elysia()
|
||||
.post(
|
||||
'/api/auth/register',
|
||||
async ({ body, jwt, set }) => {
|
||||
try {
|
||||
// Create user
|
||||
const user = await registerUser(body);
|
||||
// Create user
|
||||
const user = await registerUser(body);
|
||||
|
||||
// Generate JWT token
|
||||
const token = await jwt.sign({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
callsign: user.callsign,
|
||||
});
|
||||
|
||||
set.status = 201;
|
||||
return {
|
||||
success: true,
|
||||
token,
|
||||
user,
|
||||
};
|
||||
} catch (error) {
|
||||
if (!user) {
|
||||
set.status = 400;
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
error: 'Email already registered',
|
||||
};
|
||||
}
|
||||
|
||||
// Generate JWT token
|
||||
const token = await jwt.sign({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
callsign: user.callsign,
|
||||
});
|
||||
|
||||
set.status = 201;
|
||||
return {
|
||||
success: true,
|
||||
token,
|
||||
user,
|
||||
};
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
@@ -136,29 +136,29 @@ const app = new Elysia()
|
||||
.post(
|
||||
'/api/auth/login',
|
||||
async ({ body, jwt, set }) => {
|
||||
try {
|
||||
// Authenticate user
|
||||
const user = await authenticateUser(body.email, body.password);
|
||||
// Authenticate user
|
||||
const user = await authenticateUser(body.email, body.password);
|
||||
|
||||
// Generate JWT token
|
||||
const token = await jwt.sign({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
callsign: user.callsign,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
token,
|
||||
user,
|
||||
};
|
||||
} catch (error) {
|
||||
if (!user) {
|
||||
set.status = 401;
|
||||
return {
|
||||
success: false,
|
||||
error: 'Invalid email or password',
|
||||
};
|
||||
}
|
||||
|
||||
// Generate JWT token
|
||||
const token = await jwt.sign({
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
callsign: user.callsign,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
token,
|
||||
user,
|
||||
};
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
@@ -520,22 +520,21 @@ const app = new Elysia()
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
try {
|
||||
const { awardId } = params;
|
||||
const progress = await getAwardProgressDetails(user.id, awardId);
|
||||
const { awardId } = params;
|
||||
const progress = await getAwardProgressDetails(user.id, awardId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...progress,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Error calculating award progress', { error: error.message });
|
||||
set.status = 500;
|
||||
if (!progress) {
|
||||
set.status = 404;
|
||||
return {
|
||||
success: false,
|
||||
error: error.message || 'Failed to calculate award progress',
|
||||
error: 'Award not found',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...progress,
|
||||
};
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -548,22 +547,21 @@ const app = new Elysia()
|
||||
return { success: false, error: 'Unauthorized' };
|
||||
}
|
||||
|
||||
try {
|
||||
const { awardId } = params;
|
||||
const breakdown = await getAwardEntityBreakdown(user.id, awardId);
|
||||
const { awardId } = params;
|
||||
const breakdown = await getAwardEntityBreakdown(user.id, awardId);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...breakdown,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Error fetching award entities', { error: error.message });
|
||||
set.status = 500;
|
||||
if (!breakdown) {
|
||||
set.status = 404;
|
||||
return {
|
||||
success: false,
|
||||
error: error.message || 'Failed to fetch award entities',
|
||||
error: 'Award not found',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...breakdown,
|
||||
};
|
||||
})
|
||||
|
||||
// Health check endpoint
|
||||
@@ -572,6 +570,117 @@ const app = new Elysia()
|
||||
timestamp: new Date().toISOString(),
|
||||
}))
|
||||
|
||||
// Serve static files and SPA fallback for all non-API routes
|
||||
.get('/*', ({ request }) => {
|
||||
const url = new URL(request.url);
|
||||
const pathname = url.pathname;
|
||||
|
||||
// Don't intercept API routes
|
||||
if (pathname.startsWith('/api')) {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
|
||||
// Check for common missing assets before trying to open files
|
||||
// This prevents Elysia from trying to get file size of non-existent files
|
||||
const commonMissingFiles = ['/favicon.ico', '/robots.txt'];
|
||||
if (commonMissingFiles.includes(pathname)) {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
|
||||
// Handle SvelteKit assets path - replace %sveltekit.assets% with the assets directory
|
||||
if (pathname.startsWith('/%sveltekit.assets%/')) {
|
||||
// Extract the actual file path after %sveltekit.assets%/
|
||||
const assetPath = pathname.replace('/%sveltekit.assets%/', '');
|
||||
|
||||
try {
|
||||
// Try to serve from assets directory first
|
||||
const assetsPath = `src/frontend/build/_app/immutable/assets/${assetPath}`;
|
||||
const file = Bun.file(assetsPath);
|
||||
const exists = file.exists();
|
||||
|
||||
if (exists) {
|
||||
return new Response(file);
|
||||
}
|
||||
} catch (err) {
|
||||
// Fall through to 404
|
||||
}
|
||||
|
||||
// If not in assets, try root directory
|
||||
try {
|
||||
const rootFile = Bun.file(`src/frontend/build/${assetPath}`);
|
||||
const rootExists = rootFile.exists();
|
||||
if (rootExists) {
|
||||
return new Response(rootFile);
|
||||
}
|
||||
} catch (err) {
|
||||
// Fall through to 404
|
||||
}
|
||||
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
|
||||
// Try to serve the file from the build directory
|
||||
// Remove leading slash for file path
|
||||
const filePath = pathname === '/' ? '/index.html' : pathname;
|
||||
|
||||
try {
|
||||
const fullPath = `src/frontend/build${filePath}`;
|
||||
|
||||
// Use Bun.file() which doesn't throw for non-existent files
|
||||
const file = Bun.file(fullPath);
|
||||
const exists = file.exists();
|
||||
|
||||
if (exists) {
|
||||
// Determine content type
|
||||
const ext = filePath.split('.').pop();
|
||||
const contentTypes = {
|
||||
'js': 'application/javascript',
|
||||
'css': 'text/css',
|
||||
'html': 'text/html; charset=utf-8',
|
||||
'json': 'application/json',
|
||||
'png': 'image/png',
|
||||
'jpg': 'image/jpeg',
|
||||
'jpeg': 'image/jpeg',
|
||||
'gif': 'image/gif',
|
||||
'svg': 'image/svg+xml',
|
||||
'ico': 'image/x-icon',
|
||||
'woff': 'font/woff',
|
||||
'woff2': 'font/woff2',
|
||||
'ttf': 'font/ttf',
|
||||
};
|
||||
|
||||
const headers = {};
|
||||
if (contentTypes[ext]) {
|
||||
headers['Content-Type'] = contentTypes[ext];
|
||||
}
|
||||
|
||||
// Cache headers
|
||||
if (ext === 'html') {
|
||||
headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
|
||||
} else {
|
||||
headers['Cache-Control'] = 'public, max-age=86400';
|
||||
}
|
||||
|
||||
return new Response(file, { headers });
|
||||
}
|
||||
} catch (err) {
|
||||
// File not found or error, fall through to SPA fallback
|
||||
}
|
||||
|
||||
// SPA fallback - serve index.html for all other routes
|
||||
try {
|
||||
const indexFile = Bun.file('src/frontend/build/index.html');
|
||||
return new Response(indexFile, {
|
||||
headers: {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Cache-Control': 'no-cache, no-store, must-revalidate',
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response('Frontend not built. Run `bun run build`', { status: 503 });
|
||||
}
|
||||
})
|
||||
|
||||
// Start server
|
||||
.listen(3001);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user