Unverified Commit 4c8ff7c8 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Polyfill fetch by default (#12353)

parent 0710b6b8
...@@ -139,6 +139,11 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -139,6 +139,11 @@ const nextServerlessLoader: loader.Loader = function() {
return ` return `
import initServer from 'next-plugin-loader?middleware=on-init-server!' import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
import fetch from 'next/dist/compiled/node-fetch'
if(!global.fetch) {
global.fetch = fetch
}
${runtimeConfigImports} ${runtimeConfigImports}
${ ${
/* /*
...@@ -203,6 +208,11 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -203,6 +208,11 @@ const nextServerlessLoader: loader.Loader = function() {
return ` return `
import initServer from 'next-plugin-loader?middleware=on-init-server!' import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
import fetch from 'next/dist/compiled/node-fetch'
if(!global.fetch) {
global.fetch = fetch
}
${runtimeConfigImports} ${runtimeConfigImports}
${ ${
// this needs to be called first so its available for any other imports // this needs to be called first so its available for any other imports
......
...@@ -10,6 +10,14 @@ import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher' ...@@ -10,6 +10,14 @@ import { getRouteMatcher } from '../next-server/lib/router/utils/route-matcher'
import { getRouteRegex } from '../next-server/lib/router/utils/route-regex' import { getRouteRegex } from '../next-server/lib/router/utils/route-regex'
import { normalizePagePath } from '../next-server/server/normalize-page-path' import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants' import { SERVER_PROPS_EXPORT_ERROR } from '../lib/constants'
import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore fetch exists globally
if (!global.fetch) {
// Polyfill fetch() in the Node.js environment
// @ts-ignore fetch exists globally
global.fetch = fetch
}
const envConfig = require('../next-server/lib/runtime-config') const envConfig = require('../next-server/lib/runtime-config')
const writeFileP = promisify(writeFile) const writeFileP = promisify(writeFile)
......
...@@ -65,6 +65,14 @@ import { execOnce } from '../lib/utils' ...@@ -65,6 +65,14 @@ import { execOnce } from '../lib/utils'
import { isBlockedPage } from './utils' import { isBlockedPage } from './utils'
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp' import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
import { loadEnvConfig } from '../../lib/load-env-config' import { loadEnvConfig } from '../../lib/load-env-config'
import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore fetch exists globally
if (!global.fetch) {
// Polyfill fetch() in the Node.js environment
// @ts-ignore fetch exists globally
global.fetch = fetch
}
const getCustomRouteMatcher = pathMatch(true) const getCustomRouteMatcher = pathMatch(true)
......
import { buildStaticPaths } from '../build/utils' import { buildStaticPaths } from '../build/utils'
import { loadComponents } from '../next-server/server/load-components' import { loadComponents } from '../next-server/server/load-components'
import fetch from 'next/dist/compiled/node-fetch'
// @ts-ignore fetch exists globally
if (!global.fetch) {
// Polyfill fetch() in the Node.js environment
// @ts-ignore fetch exists globally
global.fetch = fetch
}
let workerWasUsed = false let workerWasUsed = false
......
const http = require('http')
const port = process.env.PORT || 3000
const server = new http.Server(async (req, res) => {
res.end(JSON.stringify({ foo: 'bar' }))
})
server.listen(port, err => {
if (err) {
throw err
}
console.log(`> Ready on http://localhost:${port}`)
})
export default function SSRPageWithGetInitialProps({ data }) {
return <div>{data.foo}</div>
}
SSRPageWithGetInitialProps.getInitialProps = async () => {
const port = process.env.NEXT_PUBLIC_API_PORT
const res = await fetch(`http://localhost:${port}/`)
const json = await res.json()
return {
data: json,
}
}
export default function SSRPage({ data }) {
return <div>{data.foo}</div>
}
export async function getServerSideProps() {
const port = process.env.NEXT_PUBLIC_API_PORT
const res = await fetch(`http://localhost:${port}/`)
const json = await res.json()
return {
props: {
data: json,
},
}
}
export default function StaticPage({ data }) {
return <div>{data.foo}</div>
}
export async function getStaticProps() {
const port = process.env.NEXT_PUBLIC_API_PORT
const res = await fetch(`http://localhost:${port}/`)
const json = await res.json()
return {
props: {
data: json,
},
}
}
const path = require('path')
const http = require('http')
const send = require('send')
const server = http.createServer((req, res) => {
if (req.url === '/ssr') {
return require('./.next/serverless/pages/ssr.js').render(req, res)
}
if (req.url === '/getinitialprops') {
return require('./.next/serverless/pages/getinitialprops.js').render(
req,
res
)
}
if (req.url === '/static') {
return send(
req,
path.join(__dirname, '.next/serverless/pages/static.html')
).pipe(res)
}
if (req.url.startsWith('/_next')) {
send(
req,
path.join(__dirname, '.next', req.url.split('/_next').pop())
).pipe(res)
}
})
server.listen(process.env.PORT, () => {
console.log('ready on', process.env.PORT)
})
/* eslint-env jest */
/* global jasmine */
import fs from 'fs-extra'
import { join } from 'path'
import {
killApp,
findPort,
launchApp,
initNextServerScript,
renderViaHTTP,
nextBuild,
nextStart,
} from 'next-test-utils'
import clone from 'clone'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js')
let appPort
let app
let apiServerPort
let apiServer
const startApiServer = async (optEnv = {}, opts) => {
const scriptPath = join(appDir, 'api-server.js')
apiServerPort = await findPort()
const env = Object.assign(
{},
clone(process.env),
{ PORT: `${apiServerPort}` },
optEnv
)
apiServer = await initNextServerScript(
scriptPath,
/ready on/i,
env,
/ReferenceError: options is not defined/,
opts
)
}
const startServerlessServer = async (optEnv = {}, opts) => {
const scriptPath = join(appDir, 'serverless-server.js')
appPort = await findPort()
const env = Object.assign(
{},
clone(process.env),
{ PORT: `${appPort}` },
optEnv
)
return await initNextServerScript(
scriptPath,
/ready on/i,
env,
/ReferenceError: options is not defined/,
opts
)
}
function runTests() {
it('includes polyfilled fetch when using getStaticProps', async () => {
const html = await renderViaHTTP(appPort, '/static')
expect(html).toMatch(/bar/)
})
it('includes polyfilled fetch when using getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/ssr')
expect(html).toMatch(/bar/)
})
it('includes polyfilled fetch when using getInitialProps', async () => {
const html = await renderViaHTTP(appPort, '/getinitialprops')
expect(html).toMatch(/bar/)
})
}
describe('API routes', () => {
describe('dev support', () => {
beforeAll(async () => {
appPort = await findPort()
await startApiServer()
app = await launchApp(appDir, appPort, {
env: {
NEXT_PUBLIC_API_PORT: apiServerPort,
},
})
})
afterAll(async () => {
await killApp(app)
await killApp(apiServer)
})
runTests()
})
describe('Server support', () => {
beforeAll(async () => {
await startApiServer()
await nextBuild(appDir, [], {
env: {
NEXT_PUBLIC_API_PORT: apiServerPort,
},
})
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
await killApp(apiServer)
})
runTests()
})
describe('Serverless support', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`module.exports = { target: 'serverless' }`
)
await startApiServer()
await nextBuild(appDir, [], {
env: {
NEXT_PUBLIC_API_PORT: apiServerPort,
},
})
appPort = await findPort()
app = await startServerlessServer()
})
afterAll(async () => {
await killApp(app)
await fs.remove(nextConfig)
await killApp(apiServer)
})
runTests()
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment