-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
78 lines (67 loc) · 2.34 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
const micro = require('micro')
const {parse} = require('url')
const {join} = require('path')
const next = require('next')
const raven = require('./lib/raven')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
const {matchSearchRoute, matchProductRoute, queryFromUrlParam} = require('./utils/misc')
const handleErrors = fn => async (req, res) => {
try {
return await fn(req, res)
} catch (err) {
raven.captureException(err, {req})
return micro.send(
res,
500,
'On snap! This Gluten Project robot has suffered a heart attack! The founders have been notified and will investigate ASAP.'
)
}
}
const server = micro(
handleErrors(async (req, res) => {
// WARNING WARNING WARNING WARNING
if (req.headers.host === 'tgp-front.now.sh') {
app.setAssetPrefix('https://d3kbxi1bly2af7.cloudfront.net')
} else {
// This prevents search engines from indexing anything except for the production instance
res.setHeader('x-robots-tag', 'noindex, nofollow')
app.setAssetPrefix('')
}
// WARNING WARNING WARNING WARNING
const parsedUrl = parse(req.url, true)
const {pathname, query} = parsedUrl
if (pathname === '/product' || pathname === '/search') {
res.setHeader('Location', '/')
return micro.send(res, 301)
}
const searchRoute = matchSearchRoute(pathname)
if (searchRoute) {
query.ssr = true
query.q = queryFromUrlParam(searchRoute.searchParam)
return app.render(req, res, '/search', query)
}
const productRoute = matchProductRoute(pathname)
if (productRoute) {
query.ssr = true
query.slug = productRoute.slug
return app.render(req, res, '/product', query)
}
// TODO TODO TODO TODO TODO - prevent '/product' page from loading
const rootStaticFiles = ['/robots.txt', '/sitemap.xml', '/favicon.ico']
if (rootStaticFiles.indexOf(pathname) > -1) {
const path = join(__dirname, 'static', pathname)
return app.serveStatic(req, res, path)
}
return handle(req, res, parsedUrl)
})
)
app.prepare().then(() => {
server.listen(port, err => {
if (err) throw err
// eslint-disable-next-line
console.log(`> Ready on http://localhost:${port}`)
})
})