Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@OutThisLife
Last active November 28, 2018 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OutThisLife/4084f79bf5be5227f1970fa5be89b1a2 to your computer and use it in GitHub Desktop.
Save OutThisLife/4084f79bf5be5227f1970fa5be89b1a2 to your computer and use it in GitHub Desktop.
server.ts
import * as compression from 'compression'
import * as express from 'express'
import { RequestHandlerParams } from 'express-serve-static-core'
import * as helmet from 'helmet'
import * as LRU from 'lru-cache'
import * as morgan from 'morgan'
import * as next from 'next'
import * as path from 'path'
const dev = process.env.NODE_ENV !== 'production'
if (!dev && process.env.NEW_RELIC_HOME) {
require('newrelic')
}
const dir = path.resolve(process.cwd(), 'app')
const port = parseInt(process.env.PORT, 10) || 3000
const nextApp = next({ dir, dev })
const handle = nextApp.getRequestHandler() as RequestHandlerParams
export const cache = LRU({
max: 152,
maxAge: 36e2
})
nextApp.prepare().then(() => {
const app = express()
app
.use(helmet())
.use(morgan('combined', {}))
.use(
compression({
level: 6,
filter: () => true
})
)
.use((req, res, resolve) => {
let staticUrl
if (req.url.endsWith('service-worker.js')) {
staticUrl = path.join(dir, `./.next/${req.url}`)
} else if (/(robots\.txt|favicon\.ico)$/.test(req.url)) {
staticUrl = path.join(dir, `./static/${req.url}`)
}
if (staticUrl) {
return nextApp.serveStatic(req, res, staticUrl)
}
return resolve()
})
.use(require('./schema')({ app, cache, dev }))
.use(require('./routes')({ nextApp, cache, dev }))
.get('*', handle)
.listen(port, err => {
if (err) {
console.error(err)
throw err
}
console.log(`>ready on http://[::1]:${port}\n🚀`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment