Pinafore-Web-Client-Frontend/src/server.js

90 lines
2.5 KiB
JavaScript
Raw Normal View History

import * as sapper from '../__sapper__/server.js'
import express from 'express'
import compression from 'compression'
import serveStatic from 'serve-static'
import helmet from 'helmet'
import fetch from 'node-fetch'
import inlineScriptChecksum from './inline-script/checksum'
import { sapperInlineScriptChecksums } from './server/sapperInlineScriptChecksums'
2018-01-07 00:51:25 +01:00
2018-02-09 07:29:29 +01:00
const { PORT = 4002 } = process.env
const app = express()
2018-01-07 00:51:25 +01:00
const MAX_AGE = 3600
2018-02-08 17:22:14 +01:00
// this allows us to do e.g. `fetch('/_api/blog')` on the server
2018-01-07 00:51:25 +01:00
global.fetch = (url, opts) => {
if (url[0] === '/') {
url = `http://localhost:${PORT}${url}`
}
2018-02-09 07:29:29 +01:00
return fetch(url, opts)
}
2018-01-07 00:51:25 +01:00
app.use(compression({ threshold: 0 }))
2018-01-07 00:51:25 +01:00
// CSP only needs to apply to core HTML files, not debug files
// like report.html or the JS/CSS/JSON/image files
const coreHtmlFilesOnly = (fn) => (req, res, next) => {
let coreHtml = !/\.(js|css|json|png|svg|jpe?g|map)$/.test(req.path) &&
!(/\/report.html/.test(req.path))
return coreHtml ? fn(req, res, next) : next()
}
app.use(coreHtmlFilesOnly(helmet({
contentSecurityPolicy: {
directives: {
scriptSrc: [
`'self'`,
`'sha256-${inlineScriptChecksum}'`,
...sapperInlineScriptChecksums.map(_ => `'sha256-${_}'`)
],
workerSrc: [`'self'`],
styleSrc: [`'self'`, `'unsafe-inline'`],
frameSrc: [`'none'`],
objectSrc: [`'none'`],
manifestSrc: [`'self'`]
}
},
referrerPolicy: {
policy: 'no-referrer'
2018-04-15 00:50:16 +02:00
}
})))
2018-04-15 00:50:16 +02:00
app.use(serveStatic('static', {
2018-03-21 04:46:37 +01:00
setHeaders: (res) => {
res.setHeader('Cache-Control', `public,max-age=${MAX_AGE}`)
2018-03-21 04:46:37 +01:00
}
}))
2018-01-07 00:51:25 +01:00
app.use(express.static('__sapper__/build/client/report.html'))
app.use(express.static('__sapper__/build/client/stats.json'))
2018-03-25 22:47:01 +02:00
// TODO: hack to override Sapper's default cache-control
function overrideSetHeader (req, res, next) {
const origSetHeader = res.setHeader
res.setHeader = function (key, value) {
if (key === 'Cache-Control') {
if (value === 'max-age=31536000, immutable') { // webpack assets
return origSetHeader.apply(this, ['Cache-Control', 'public,max-age=31536000,immutable'])
}
if (value === 'max-age=600') { // HTML files
return origSetHeader.apply(this, ['Cache-Control', `public,max-age=${MAX_AGE}`])
}
}
return origSetHeader.apply(this, arguments)
}
return next()
}
app.use(overrideSetHeader, sapper.middleware())
2018-01-07 00:51:25 +01:00
app.listen(PORT, () => {
2018-02-09 07:29:29 +01:00
console.log(`listening on port ${PORT}`)
})
// Handle SIGINT (source: https://git.io/vhJgF)
process.on('SIGINT', function () {
process.exit(0)
})