generated from JoviDeCroock/product-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
67 lines (58 loc) · 1.81 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
const polka = require('polka');
const path = require('path');
const fs = require('fs');
const sirv = require('sirv');
const compression = require('compression');
const cookieParser = require('cookie-parser');
const prerender = require('./dist/server').default;
const PRODUCTION = process.env.NODE_ENV === 'production';
const dist = path.resolve(__dirname, 'dist');
const distFiles = fs.readdirSync(dist);
const jsEntry = distFiles.find(
file => file.startsWith('main') && file.endsWith('.js')
);
const cssEntry = distFiles.find(
file => file.startsWith('main') && file.endsWith('.css')
);
const fontEntry = distFiles.find(file => file.endsWith('.woff'));
const server = polka();
server.use(compression());
// serve static files from public/*
server.use((req, res, next) => {
res._requestHeaders = req.headers;
next();
});
server.use(
sirv('dist', {
dev: !PRODUCTION,
extensions: [],
maxAge: 3600,
etag: true,
setHeaders(res, path, stats) {
const etag = res._requestHeaders['if-none-match'];
const computedEtag = `W/"${stats.size}-${stats.mtime.getTime()}"`;
if (etag && etag === computedEtag) {
res.writeHead(304);
res.end();
// disable sirv's normal response & piping:
res.writeHead = res.write = res.end = () => {};
}
},
})
);
server.use('/', cookieParser(), (req, res, next) => {
res.setHeader('Cache-Control', 'max-age=3600');
res.setHeader('Content-Type', 'text/html;charset=utf-8');
res.setHeader('X-Content-Type-Options', 'nosniff');
prerender(req, jsEntry, cssEntry, fontEntry)
.then(html => {
res.response = null;
res.end(html);
})
.catch(error => {
console.log('error', error);
if (error.then) error.then(console.log);
next(error.stack);
});
});
server.listen(process.env.PORT || 5000);