Skip to content

Instantly share code, notes, and snippets.

@josiahwiebe
Created February 9, 2018 15:48
Show Gist options
  • Save josiahwiebe/3807fa1b8d563f50fe47d32cc7d07aaf to your computer and use it in GitHub Desktop.
Save josiahwiebe/3807fa1b8d563f50fe47d32cc7d07aaf to your computer and use it in GitHub Desktop.
Express NextJS + API Example
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.status(200).json({message: 'hello from api'})
})
module.exports = router
import React from 'react'
export default () => <div>a</div>
import React from 'react'
import Link from 'next/link'
export default () => (
<ul>
<li>
<Link href='/a'>
<a>a</a>
</Link>
</li>
</ul>
)
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const api = require('./api')
app.prepare().then(() => {
const server = express()
server.use('/api', api)
server.get('/a', (req, res) => app.render(req, res, '/a', req.query))
server.get('*', (req, res) => handle(req, res))
server.listen(port, (err) => {
if (err) throw err
console.info(`> Next.js is running on http://localhost:${port}`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment