-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
94 lines (83 loc) · 2.45 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env node
import os from 'node:os'
import compression from 'compression'
import consola from 'consola'
import express from 'express'
import rateLimit from 'express-rate-limit'
import morgan from 'morgan'
import { resolve } from 'pathe'
import { env, isDevelopment } from 'std-env'
// Short-circuit the type-checking of the built output.
const BUILD_PATH = resolve('dist/server/index.js')
const PORT = Number.parseInt(env.PORT || '3000')
const app = express()
app.use(compression({ level: 6, threshold: 0 }))
app.disable('x-powered-by')
if (env.ENABLE_RATE_LIMIT === 'true') {
app.use(
rateLimit({
windowMs: 60 * 1000 * 15, // 15 minutes
max: 1000, // limit request for each IP per window
})
)
}
if (isDevelopment) {
consola.withTag('server').log('Starting development server')
const viteDevServer = await import('vite').then((vite) =>
vite.createServer({
server: { middlewareMode: true },
})
)
app.use(viteDevServer.middlewares)
app.use(async (req, res, next) => {
try {
const source = await viteDevServer.ssrLoadModule('./server/app.ts')
return await source.app(req, res, next)
} catch (error) {
if (typeof error === 'object' && error instanceof Error) {
viteDevServer.ssrFixStacktrace(error)
}
next(error)
}
})
} else {
consola.withTag('server').log('Starting production server')
app.use(
'/assets',
express.static('dist/client/assets', {
immutable: true,
maxAge: '1y',
setHeaders: (res, path) => {
if (path.endsWith('.html')) {
res.set('Cache-Control', 'public, max-age=0, must-revalidate')
}
},
})
)
app.use(express.static('dist/client', { maxAge: '1h' }))
app.use(await import(BUILD_PATH).then((mod) => mod.app))
}
app.use(
morgan('short', {
skip: (req) => req.method === 'HEAD',
stream: {
write: (message) => consola.withTag('server').log(message.trim()),
},
})
)
function getLocalIpAddress() {
return Object.values(os.networkInterfaces())
.flat()
.find((ip) => ip?.family === 'IPv4' && !ip.internal)?.address
}
const onListen = () => {
const address = getLocalIpAddress()
const localUrl = `http://localhost:${PORT}`
const networkUrl = address ? `http://${address}:${PORT}` : null
if (networkUrl) {
consola.withTag('server').log(`Host: ${localUrl} (${networkUrl})`)
} else {
consola.withTag('server').log(localUrl)
}
}
app.listen(PORT, () => onListen())