Skip to content

Instantly share code, notes, and snippets.

@ugiacoman
Created March 30, 2017 17:56
Show Gist options
  • Save ugiacoman/007a6349bb1da7349b6b538bf78fef7f to your computer and use it in GitHub Desktop.
Save ugiacoman/007a6349bb1da7349b6b538bf78fef7f to your computer and use it in GitHub Desktop.
next.js + custom server + api ; nasty I know :)
const { parse } = require('url')
const next = require('next')
const pathMatch = require('path-match')
const express = require('express')
const compression = require('compression')
require('dotenv').config()
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const route = pathMatch()
const match = route('/journal/:home/:articlePath/:file')
app.prepare()
.then(() => {
const server = express()
server.use(compression())
server.get('/api/:request/:query', (req, res) => {
// INSERT GITHUB API LOGIC IN HERE
res.send(`${req.params.request} and ${req.params.query}`)
})
server.get('*', (req, res) => {
const { pathname } = parse(req.url)
const params = match(pathname)
if (params === false) {
return handle(req, res)
}
app.render(req, res, '/journal', params)
})
server.listen(process.env.PORT, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${process.env.PORT}`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment