rsnext/examples/custom-server-fastify/server.js
Joe Haddad 53f4f82e4c
Catch all requests in custom server (#8704)
Some users aren't aware they need to edit their custom server to support various HTTP Methods (e.g. POST for API Routes).

Instead, we should just handle all HTTP Methods out-of-the-box.

---

Closes #8237
2019-09-11 10:23:41 -04:00

52 lines
1.3 KiB
JavaScript

const fastify = require('fastify')({ logger: { level: 'error' } })
const Next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
fastify.register((fastify, opts, next) => {
const app = Next({ dev })
app
.prepare()
.then(() => {
if (dev) {
fastify.get('/_next/*', (req, reply) => {
return app.handleRequest(req.req, reply.res).then(() => {
reply.sent = true
})
})
}
fastify.get('/a', (req, reply) => {
return app.render(req.req, reply.res, '/a', req.query).then(() => {
reply.sent = true
})
})
fastify.get('/b', (req, reply) => {
return app.render(req.req, reply.res, '/b', req.query).then(() => {
reply.sent = true
})
})
fastify.all('/*', (req, reply) => {
return app.handleRequest(req.req, reply.res).then(() => {
reply.sent = true
})
})
fastify.setNotFoundHandler((request, reply) => {
return app.render404(request.req, reply.res).then(() => {
reply.sent = true
})
})
next()
})
.catch(err => next(err))
})
fastify.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})