Unverified Commit 02405e22 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix getServerSideProps hanging in dev on early end (#33366)

This fixes the case where calling `res.end()` is `getServerSideProps` would cause the request to hang in development due to our `Proxy` around `res` causing internal `ServerResponse` fields to not be available ([related post](https://javascript.info/proxy#built-in-objects-internal-slots)). I also migrated our `getServerSideProps` test suite to an e2e suite with a test for this case. 

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`

Fixes: https://github.com/vercel/next.js/issues/15118
Fixes: https://github.com/vercel/next.js/issues/32824
Closes: https://github.com/vercel/next.js/pull/33129
parent 10c4f5d1
......@@ -961,7 +961,15 @@ export async function renderToHTML(
warn(message)
}
}
return Reflect.get(obj, prop, receiver)
const value = Reflect.get(obj, prop, receiver)
// since ServerResponse uses internal fields which
// proxy can't map correctly we need to ensure functions
// are bound correctly while being proxied
if (typeof value === 'function') {
return value.bind(obj)
}
return value
},
})
}
......
import Link from 'next/link'
import path from 'path'
import fs from 'fs'
import findUp from 'find-up'
export async function getServerSideProps() {
const text = fs
.readFileSync(
findUp.sync('world.txt', {
// prevent webpack from intercepting
// eslint-disable-next-line no-eval
cwd: eval(`__dirname`),
}),
'utf8'
)
.readFileSync(path.join(process.cwd(), 'world.txt'), 'utf8')
.trim()
return {
......
export function getServerSideProps({ res }) {
res.statusCode = 200
res.end('hello from gssp')
return {
props: {},
}
}
export default function Page(props) {
return <p>early request end</p>
}
/* eslint-env jest */
import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import escapeRegex from 'escape-string-regexp'
import fs from 'fs-extra'
import {
check,
fetchViaHTTP,
findPort,
File,
getBrowserBodyText,
getRedboxHeader,
killApp,
launchApp,
nextBuild,
nextStart,
normalizeRegEx,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
import webdriver from 'next-webdriver'
import { NextInstance } from 'test/lib/next-modes/base'
const appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
const appDir = join(__dirname, '../app')
let app
let appPort
let buildId
let stderr
let next: NextInstance
const expectedManifestRoutes = () => [
{
......@@ -99,6 +91,12 @@ const expectedManifestRoutes = () => [
),
page: '/default-revalidate',
},
{
dataRouteRegex: `^\\/_next\\/data\\/${escapeRegex(
buildId
)}\\/early-request-end.json$`,
page: '/early-request-end',
},
{
dataRouteRegex: normalizeRegEx(
`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/enoent.json$`
......@@ -197,7 +195,7 @@ const expectedManifestRoutes = () => [
},
]
const navigateTest = (dev = false) => {
const navigateTest = () => {
it('should navigate between pages successfully', async () => {
const toBuild = [
'/',
......@@ -208,9 +206,9 @@ const navigateTest = (dev = false) => {
'/blog/post-1/comment-1',
]
await Promise.all(toBuild.map((pg) => renderViaHTTP(appPort, pg)))
await Promise.all(toBuild.map((pg) => renderViaHTTP(next.url, pg)))
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
......@@ -284,23 +282,29 @@ const navigateTest = (dev = false) => {
}
const runTests = (dev = false) => {
navigateTest(dev)
navigateTest()
it('should work with early request ending', async () => {
const res = await fetchViaHTTP(next.url, '/early-request-end')
expect(res.status).toBe(200)
expect(await res.text()).toBe('hello from gssp')
})
it('should render correctly when notFound is false (non-dynamic)', async () => {
const res = await fetchViaHTTP(appPort, '/not-found')
const res = await fetchViaHTTP(next.url, '/not-found')
expect(res.status).toBe(200)
})
it('should render 404 correctly when notFound is returned (non-dynamic)', async () => {
const res = await fetchViaHTTP(appPort, '/not-found', { hiding: true })
const res = await fetchViaHTTP(next.url, '/not-found', { hiding: true })
expect(res.status).toBe(404)
expect(await res.text()).toContain('This page could not be found')
})
it('should render 404 correctly when notFound is returned client-transition (non-dynamic)', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/not-found?hiding=true')
......@@ -314,13 +318,13 @@ const runTests = (dev = false) => {
})
it('should render correctly when notFound is false (dynamic)', async () => {
const res = await fetchViaHTTP(appPort, '/not-found/first')
const res = await fetchViaHTTP(next.url, '/not-found/first')
expect(res.status).toBe(200)
})
it('should render 404 correctly when notFound is returned (dynamic)', async () => {
const res = await fetchViaHTTP(appPort, '/not-found/first', {
const res = await fetchViaHTTP(next.url, '/not-found/first', {
hiding: true,
})
......@@ -329,7 +333,7 @@ const runTests = (dev = false) => {
})
it('should render 404 correctly when notFound is returned client-transition (dynamic)', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await browser.eval(`(function() {
window.beforeNav = 1
window.next.router.push('/not-found/first?hiding=true')
......@@ -343,17 +347,17 @@ const runTests = (dev = false) => {
})
it('should SSR normal page correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const html = await renderViaHTTP(next.url, '/')
expect(html).toMatch(/hello.*?world/)
})
it('should SSR getServerSideProps page correctly', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
const html = await renderViaHTTP(next.url, '/blog/post-1')
expect(html).toMatch(/Post:.*?post-1/)
})
it('should handle throw ENOENT correctly', async () => {
const res = await fetchViaHTTP(appPort, '/enoent')
const res = await fetchViaHTTP(next.url, '/enoent')
const html = await res.text()
if (dev) {
......@@ -366,19 +370,19 @@ const runTests = (dev = false) => {
})
it('should have gssp in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const html = await renderViaHTTP(next.url, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gssp).toBe(true)
})
it('should not have gssp in __NEXT_DATA__ for non-GSSP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const html = await renderViaHTTP(next.url, '/normal')
const $ = cheerio.load(html)
expect('gssp' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should supply query values SSR', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1?hello=world')
const html = await renderViaHTTP(next.url, '/blog/post-1?hello=world')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ post: 'post-1' })
......@@ -387,7 +391,7 @@ const runTests = (dev = false) => {
})
it('should supply params values for catchall correctly', async () => {
const html = await renderViaHTTP(appPort, '/catchall/first')
const html = await renderViaHTTP(next.url, '/catchall/first')
const $ = cheerio.load(html)
const params = $('#params').text()
expect(JSON.parse(params)).toEqual({ path: ['first'] })
......@@ -395,7 +399,10 @@ const runTests = (dev = false) => {
expect(JSON.parse(query)).toEqual({ path: ['first'] })
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/catchall/first.json`)
await renderViaHTTP(
next.url,
`/_next/data/${buildId}/catchall/first.json`
)
)
expect(data.pageProps.params).toEqual({ path: ['first'] })
......@@ -403,7 +410,7 @@ const runTests = (dev = false) => {
it('should have original req.url for /_next/data request dynamic page', async () => {
const curUrl = `/_next/data/${buildId}/blog/post-1.json`
const data = await renderViaHTTP(appPort, curUrl)
const data = await renderViaHTTP(next.url, curUrl)
const { appProps, pageProps } = JSON.parse(data)
expect(pageProps.resolvedUrl).toEqual('/blog/post-1')
......@@ -418,7 +425,7 @@ const runTests = (dev = false) => {
it('should have original req.url for /_next/data request dynamic page with query', async () => {
const curUrl = `/_next/data/${buildId}/blog/post-1.json`
const data = await renderViaHTTP(appPort, curUrl, { hello: 'world' })
const data = await renderViaHTTP(next.url, curUrl, { hello: 'world' })
const { appProps, pageProps } = JSON.parse(data)
expect(pageProps.resolvedUrl).toEqual('/blog/post-1?hello=world')
......@@ -433,7 +440,7 @@ const runTests = (dev = false) => {
it('should have original req.url for /_next/data request', async () => {
const curUrl = `/_next/data/${buildId}/something.json`
const data = await renderViaHTTP(appPort, curUrl)
const data = await renderViaHTTP(next.url, curUrl)
const { appProps, pageProps } = JSON.parse(data)
expect(pageProps.resolvedUrl).toEqual('/something')
......@@ -448,7 +455,7 @@ const runTests = (dev = false) => {
it('should have original req.url for /_next/data request with query', async () => {
const curUrl = `/_next/data/${buildId}/something.json`
const data = await renderViaHTTP(appPort, curUrl, { hello: 'world' })
const data = await renderViaHTTP(next.url, curUrl, { hello: 'world' })
const { appProps, pageProps } = JSON.parse(data)
expect(pageProps.resolvedUrl).toEqual('/something?hello=world')
......@@ -462,7 +469,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1')
const html = await renderViaHTTP(next.url, '/blog/post-1')
const $ = cheerio.load(html)
expect($('#app-url').text()).toContain('/blog/post-1')
expect(JSON.parse($('#app-query').text())).toEqual({ post: 'post-1' })
......@@ -471,7 +478,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit dynamic page rewrite direct', async () => {
const html = await renderViaHTTP(appPort, '/blog-post-1')
const html = await renderViaHTTP(next.url, '/blog-post-1')
const $ = cheerio.load(html)
expect($('#app-url').text()).toContain('/blog-post-1')
expect(JSON.parse($('#app-query').text())).toEqual({ post: 'post-1' })
......@@ -480,7 +487,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit dynamic page rewrite direct with internal query', async () => {
const html = await renderViaHTTP(appPort, '/blog-post-2')
const html = await renderViaHTTP(next.url, '/blog-post-2')
const $ = cheerio.load(html)
expect($('#app-url').text()).toContain('/blog-post-2')
expect(JSON.parse($('#app-query').text())).toEqual({
......@@ -492,7 +499,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit dynamic page rewrite param', async () => {
const html = await renderViaHTTP(appPort, '/blog-post-3')
const html = await renderViaHTTP(next.url, '/blog-post-3')
const $ = cheerio.load(html)
expect($('#app-url').text()).toContain('/blog-post-3')
expect(JSON.parse($('#app-query').text())).toEqual({
......@@ -504,7 +511,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit dynamic page with query', async () => {
const html = await renderViaHTTP(appPort, '/blog/post-1', {
const html = await renderViaHTTP(next.url, '/blog/post-1', {
hello: 'world',
})
const $ = cheerio.load(html)
......@@ -518,7 +525,7 @@ const runTests = (dev = false) => {
})
it('should have correct req.url and query for direct visit', async () => {
const html = await renderViaHTTP(appPort, '/something')
const html = await renderViaHTTP(next.url, '/something')
const $ = cheerio.load(html)
expect($('#app-url').text()).toContain('/something')
expect(JSON.parse($('#app-query').text())).toEqual({})
......@@ -528,7 +535,7 @@ const runTests = (dev = false) => {
it('should return data correctly', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/something.json`)
await renderViaHTTP(next.url, `/_next/data/${buildId}/something.json`)
)
expect(data.pageProps.world).toBe('world')
})
......@@ -536,7 +543,7 @@ const runTests = (dev = false) => {
it('should pass query for data request', async () => {
const data = JSON.parse(
await renderViaHTTP(
appPort,
next.url,
`/_next/data/${buildId}/something.json?another=thing`
)
)
......@@ -545,18 +552,18 @@ const runTests = (dev = false) => {
it('should return data correctly for dynamic page', async () => {
const data = JSON.parse(
await renderViaHTTP(appPort, `/_next/data/${buildId}/blog/post-1.json`)
await renderViaHTTP(next.url, `/_next/data/${buildId}/blog/post-1.json`)
)
expect(data.pageProps.post).toBe('post-1')
})
it('should return data correctly when props is a promise', async () => {
const html = await renderViaHTTP(appPort, `/promise`)
const html = await renderViaHTTP(next.url, `/promise`)
expect(html).toMatch(/hello.*?promise/)
})
it('should navigate to a normal page and back', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
......@@ -567,7 +574,7 @@ const runTests = (dev = false) => {
})
it('should load a fast refresh page', async () => {
const browser = await webdriver(appPort, '/refresh')
const browser = await webdriver(next.url, '/refresh')
expect(
await check(
() => browser.elementByCss('p').text(),
......@@ -579,7 +586,7 @@ const runTests = (dev = false) => {
it('should provide correct query value for dynamic page', async () => {
const html = await renderViaHTTP(
appPort,
next.url,
'/blog/post-1?post=something-else'
)
const $ = cheerio.load(html)
......@@ -588,7 +595,7 @@ const runTests = (dev = false) => {
})
it('should parse query values on mount correctly', async () => {
const browser = await webdriver(appPort, '/blog/post-1?another=value')
const browser = await webdriver(next.url, '/blog/post-1?another=value')
await waitFor(2000)
const text = await browser.elementByCss('#query').text()
expect(text).toMatch(/another.*?value/)
......@@ -596,7 +603,7 @@ const runTests = (dev = false) => {
})
it('should pass query for data request on navigation', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await browser.eval('window.beforeNav = true')
await browser.elementByCss('#something-query').click()
await browser.waitForElementByCss('#initial-query')
......@@ -608,7 +615,7 @@ const runTests = (dev = false) => {
})
it('should reload page on failed data request', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await waitFor(500)
await browser.eval('window.beforeClick = "abc"')
await browser.elementByCss('#broken-post').click()
......@@ -622,23 +629,23 @@ const runTests = (dev = false) => {
})
it('should always call getServerSideProps without caching', async () => {
const initialRes = await fetchViaHTTP(appPort, '/something')
const initialRes = await fetchViaHTTP(next.url, '/something')
const initialHtml = await initialRes.text()
expect(initialHtml).toMatch(/hello.*?world/)
const newRes = await fetchViaHTTP(appPort, '/something')
const newRes = await fetchViaHTTP(next.url, '/something')
const newHtml = await newRes.text()
expect(newHtml).toMatch(/hello.*?world/)
expect(initialHtml !== newHtml).toBe(true)
const newerRes = await fetchViaHTTP(appPort, '/something')
const newerRes = await fetchViaHTTP(next.url, '/something')
const newerHtml = await newerRes.text()
expect(newerHtml).toMatch(/hello.*?world/)
expect(newHtml !== newerHtml).toBe(true)
})
it('should not re-call getServerSideProps when updating query', async () => {
const browser = await webdriver(appPort, '/something?hello=world')
const browser = await webdriver(next.url, '/something?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text()
......@@ -655,7 +662,7 @@ const runTests = (dev = false) => {
})
it('should dedupe server data requests', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await waitFor(2000)
// Keep clicking on the link
......@@ -682,8 +689,8 @@ const runTests = (dev = false) => {
if (dev) {
it('should not show warning from url prop being returned', async () => {
const urlPropPage = join(appDir, 'pages/url-prop.js')
await fs.writeFile(
const urlPropPage = 'pages/url-prop.js'
await next.patchFile(
urlPropPage,
`
export async function getServerSideProps() {
......@@ -698,16 +705,16 @@ const runTests = (dev = false) => {
`
)
const html = await renderViaHTTP(appPort, '/url-prop')
await fs.remove(urlPropPage)
expect(stderr).not.toMatch(
const html = await renderViaHTTP(next.url, '/url-prop')
await next.deleteFile(urlPropPage)
expect(next.cliOutput).not.toMatch(
/The prop `url` is a reserved prop in Next.js for legacy reasons and will be overridden on page \/url-prop/
)
expect(html).toMatch(/url:.*?something/)
})
it('should show error for extra keys returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/invalid-keys')
const html = await renderViaHTTP(next.url, '/invalid-keys')
expect(html).toContain(
`Additional keys were returned from \`getServerSideProps\`. Properties intended for your component must be nested under the \`props\` key, e.g.:`
)
......@@ -717,14 +724,14 @@ const runTests = (dev = false) => {
})
it('should show error for invalid JSON returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/non-json')
const html = await renderViaHTTP(next.url, '/non-json')
expect(html).toContain(
'Error serializing `.time` returned from `getServerSideProps`'
)
})
it('should show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#non-json').click()
await check(
......@@ -734,14 +741,14 @@ const runTests = (dev = false) => {
})
it('should show error for accessing res after gssp returns', async () => {
const html = await renderViaHTTP(appPort, '/promise/mutate-res')
const html = await renderViaHTTP(next.url, '/promise/mutate-res')
expect(html).toContain(
`You should not access 'res' after getServerSideProps resolves`
)
})
it('should show error for accessing res through props promise after gssp returns', async () => {
const html = await renderViaHTTP(appPort, '/promise/mutate-res-props')
const html = await renderViaHTTP(next.url, '/promise/mutate-res-props')
expect(html).toContain(
`You should not access 'res' after getServerSideProps resolves`
)
......@@ -749,19 +756,19 @@ const runTests = (dev = false) => {
it('should only warn for accessing res if not streaming', async () => {
const html = await renderViaHTTP(
appPort,
next.url,
'/promise/mutate-res-no-streaming'
)
expect(html).not.toContain(
`You should not access 'res' after getServerSideProps resolves`
)
expect(stderr).toContain(
expect(next.cliOutput).toContain(
`You should not access 'res' after getServerSideProps resolves`
)
})
} else {
it('should not fetch data on mount', async () => {
const browser = await webdriver(appPort, '/blog/post-100')
const browser = await webdriver(next.url, '/blog/post-100')
await browser.eval('window.thisShouldStay = true')
await waitFor(2 * 1000)
const val = await browser.eval('window.thisShouldStay')
......@@ -769,8 +776,8 @@ const runTests = (dev = false) => {
})
it('should output routes-manifest correctly', async () => {
const { dataRoutes } = await fs.readJSON(
join(appDir, '.next/routes-manifest.json')
const { dataRoutes } = JSON.parse(
await next.readFile('.next/routes-manifest.json')
)
for (const route of dataRoutes) {
route.dataRouteRegex = normalizeRegEx(route.dataRouteRegex)
......@@ -780,13 +787,13 @@ const runTests = (dev = false) => {
})
it('should set default caching header', async () => {
const resPage = await fetchViaHTTP(appPort, `/something`)
const resPage = await fetchViaHTTP(next.url, `/something`)
expect(resPage.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
const resData = await fetchViaHTTP(
appPort,
next.url,
`/_next/data/${buildId}/something.json`
)
expect(resData.headers.get('cache-control')).toBe(
......@@ -795,92 +802,52 @@ const runTests = (dev = false) => {
})
it('should respect custom caching header', async () => {
const resPage = await fetchViaHTTP(appPort, `/custom-cache`)
const resPage = await fetchViaHTTP(next.url, `/custom-cache`)
expect(resPage.headers.get('cache-control')).toBe('public, max-age=3600')
const resData = await fetchViaHTTP(
appPort,
next.url,
`/_next/data/${buildId}/custom-cache.json`
)
expect(resData.headers.get('cache-control')).toBe('public, max-age=3600')
})
it('should not show error for invalid JSON returned from getServerSideProps', async () => {
const html = await renderViaHTTP(appPort, '/non-json')
const html = await renderViaHTTP(next.url, '/non-json')
expect(html).not.toContain('Error serializing')
expect(html).toContain('hello ')
})
it('should not show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/')
const browser = await webdriver(next.url, '/')
await browser.elementByCss('#non-json').click()
await check(() => getBrowserBodyText(browser), /hello /)
})
it('should not show error for accessing res after gssp returns', async () => {
const html = await renderViaHTTP(appPort, '/promise/mutate-res')
const html = await renderViaHTTP(next.url, '/promise/mutate-res')
expect(html).toMatch(/hello.*?res/)
})
it('should not warn for accessing res after gssp returns', async () => {
const html = await renderViaHTTP(appPort, '/promise/mutate-res')
const html = await renderViaHTTP(next.url, '/promise/mutate-res')
expect(html).toMatch(/hello.*?res/)
})
}
}
describe('getServerSideProps', () => {
describe('dev mode', () => {
beforeAll(async () => {
stderr = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStderr(msg) {
stderr += msg
},
})
buildId = 'development'
})
afterAll(() => killApp(app))
runTests(true)
})
describe('serverless mode', () => {
beforeAll(async () => {
await nextConfig.replace(
'// replace me',
`target: 'experimental-serverless-trace', `
)
await nextBuild(appDir)
stderr = ''
appPort = await findPort()
app = await nextStart(appDir, appPort, {
onStderr(msg) {
stderr += msg
},
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
beforeAll(async () => {
next = await createNext({
files: {
pages: new FileRef(join(appDir, 'pages')),
'world.txt': new FileRef(join(appDir, 'world.txt')),
'next.config.js': new FileRef(join(appDir, 'next.config.js')),
},
})
runTests()
buildId = next.buildId
})
afterAll(() => next.destroy())
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir, [], { stdout: true })
appPort = await findPort()
app = await nextStart(appDir, appPort)
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(() => killApp(app))
runTests()
})
runTests((global as any).isNextDev)
})
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