-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
88 lines (76 loc) · 2.73 KB
/
server.js
File metadata and controls
88 lines (76 loc) · 2.73 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
require('dotenv').config({ path: `${__dirname}/.env.local` });
const Next = require('next');
const https = require('https');
const http = require('http');
const url = require('url');
const fs = require('fs');
const logger = require('./lib/logger');
const dev = process.env.NODE_ENV === 'development';
const protocol = process.env.NEXT_PROTOCOL;
const hostname = process.env.NEXT_HOSTNAME;
const app = Next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
let server;
let options = {};
if(protocol == 'http') {
server = http;
logger.warn('Running in HTTP mode - not secure!');
} else {
server = https;
try {
options = {
key: fs.readFileSync(`${__dirname}/certificates/privkey.pem`),
cert: fs.readFileSync(`${__dirname}/certificates/fullchain.pem`)
};
logger.success('SSL certificates loaded successfully');
} catch (err) {
logger.error('Failed to load SSL certificates:', err.message);
process.exit(1);
}
}
const startTime = Date.now();
server.createServer(options, async (req, res) => {
const requestStart = Date.now();
const method = req.method || 'GET';
const path = req.url || '/';
// Log request
res.on('finish', () => {
const duration = Date.now() - requestStart;
logger.http(method, path, res.statusCode, duration);
});
try {
const parsedUrl = url.parse(req.url, true);
await handle(req, res, parsedUrl);
} catch (err) {
logger.error('Error occurred handling request', path, err.message);
if (err.stack) {
logger.debug('Stack trace:', err.stack);
}
res.statusCode = 500;
res.end('internal server error');
}
}).listen(protocol == 'https' ? 443 : 80, (err) => {
if (err) {
logger.error('Failed to start server:', err.message);
throw err;
}
const startupTime = Date.now() - startTime;
const port = protocol == 'https' ? 443 : 80;
// Display startup information in a nice box
logger.startup({
protocol: protocol,
hostname: hostname,
environment: dev ? 'development' : 'production',
port: port,
startupTime: startupTime
});
logger.success(`Server is ready and listening on ${protocol}://${hostname}:${port}`);
});
}).catch((err) => {
logger.error('Failed to prepare Next.js app:', err.message);
if (err.stack) {
logger.debug('Stack trace:', err.stack);
}
process.exit(1);
});