rsnext/test/integration/custom-server/server.js
Javi Velasco 59f7676966
Fix running server with Polyfilled fetch (#32368)
**Note**: This PR is applying again changes landed #31935 that were reverted from an investigation.

This PR fixes #30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since #31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
2021-12-13 18:30:24 +00:00

61 lines
1.4 KiB
JavaScript

if (process.env.POLYFILL_FETCH) {
global.fetch = require('node-fetch').default
}
const http = require('http')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const dir = __dirname
const port = process.env.PORT || 3000
const app = next({ dev, dir })
const handleNextRequests = app.getRequestHandler()
app.prepare().then(() => {
const server = new http.Server(async (req, res) => {
if (req.url === '/no-query') {
return app.render(req, res, '/no-query')
}
if (/setAssetPrefix/.test(req.url)) {
app.setAssetPrefix(`http://127.0.0.1:${port}`)
} else if (/setEmptyAssetPrefix/.test(req.url)) {
app.setAssetPrefix(null)
} else {
// This is to support multi-zones support in localhost
// and may be in staging deployments
app.setAssetPrefix('')
}
if (/test-index-hmr/.test(req.url)) {
return app.render(req, res, '/index')
}
if (/dashboard/.test(req.url)) {
return app.render(req, res, '/dashboard')
}
if (/static\/hello\.text/.test(req.url)) {
return app.render(req, res, '/static/hello.text')
}
if (/no-slash/.test(req.url)) {
try {
await app.render(req, res, 'dashboard')
} catch (err) {
res.end(err.message)
}
}
handleNextRequests(req, res)
})
server.listen(port, (err) => {
if (err) {
throw err
}
console.log(`> Ready on http://localhost:${port}`)
})
})