Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error handling in the SSR middleware #31057

Merged
merged 1 commit into from Nov 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -57,10 +57,6 @@ export default async function middlewareRSCLoader(this: any) {
throw new Error('Your page must export a \`default\` component')
}

function renderError(err, status) {
return new Response(err.toString(), {status})
}

function wrapReadable(readable) {
const encoder = new TextEncoder()
const transformStream = new TransformStream()
Expand Down Expand Up @@ -104,15 +100,10 @@ export default async function middlewareRSCLoader(this: any) {
const Component = Page`
}

function render(request) {
async function render(request) {
const url = request.nextUrl
const query = Object.fromEntries(url.searchParams)

if (Document.getInitialProps) {
const err = new Error('Document.getInitialProps is not supported with server components, please remove it from pages/_document')
return renderError(err, 500)
}

// Preflight request
if (request.method === 'HEAD') {
return new Response('OK.', {
Expand Down Expand Up @@ -172,18 +163,27 @@ export default async function middlewareRSCLoader(this: any) {
const writer = transformStream.writable.getWriter()
const encoder = new TextEncoder()

renderToHTML(
{ url: url.pathname },
{},
url.pathname,
query,
renderOpts
).then(result => {
try {
const result = await renderToHTML(
{ url: url.pathname },
{},
url.pathname,
query,
renderOpts
)
result.pipe({
write: str => writer.write(encoder.encode(str)),
end: () => writer.close()
})
})
} catch (err) {
return new Response(
(err || 'An error occurred while rendering ' + url.pathname + '.').toString(),
{
status: 500,
headers: { 'x-middleware-ssr': '1' }
}
)
}

return new Response(transformStream.readable, {
headers: { 'x-middleware-ssr': '1' }
Expand Down
Expand Up @@ -190,7 +190,7 @@ const documentSuite = {

expect(res.status).toBe(500)
expect(html).toContain(
'Document.getInitialProps is not supported with server components, please remove it from pages/_document'
'Error: `getInitialProps` in Document component is not supported with `concurrentFeatures` enabled.'
)
})
},
Expand Down