Skip to content

Instantly share code, notes, and snippets.

@d1y
Last active August 26, 2019 06:05
Show Gist options
  • Select an option

  • Save d1y/9b8eddeabd3d92a4f4ff4e6472e809a6 to your computer and use it in GitHub Desktop.

Select an option

Save d1y/9b8eddeabd3d92a4f4ff4e6472e809a6 to your computer and use it in GitHub Desktop.
[Nextjs] A nextjs middle proxy
/*
** currentpath: /pages/path.js
*/
import { withRouter } from 'next/router'
export default withRouter((router)=> (
<>
<p>the id is { router.query.id }</p>
</>
))
/*
** use `koa` and `koa-router`
** https://github.com/zeit/next.js#custom-server-and-routing
*/
const koa = require('koa')
const Router = require('koa-router')
const next = require('next')
// check the env is dev
const dev = process.env.NODE_ENV == 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(()=> {
const server = new Koa()
const router = new Router()
router.get('/path/:id', async ctx => {
const id = ctx.params.id
await handle( ctx.req, ctx.res, {
pathname: '/path',
query: { id }
}
ctx.respond = false
})
server.use(router.routes())
server.use(async (ctx, next) => {
await handle(ctx.req, ctx.res)
ctx.respond = false
})
server.listen(3000, () => {
console.log('koa-server run in :3000')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment