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

Update to make sure preview mode works with getServerSideProps #10813

Merged
merged 4 commits into from Mar 4, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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
29 changes: 19 additions & 10 deletions packages/next/next-server/server/next-server.ts
Expand Up @@ -905,6 +905,13 @@ export default class Server {
})
}

const previewData = tryGetPreviewData(
ijjk marked this conversation as resolved.
Show resolved Hide resolved
req,
res,
this.renderOpts.previewProps
)
const isPreviewMode = previewData !== false

// non-spr requests should render like normal
if (!isSSG) {
// handle serverless
Expand All @@ -923,7 +930,7 @@ export default class Server {
!this.renderOpts.dev
? {
revalidate: -1,
private: false, // Leave to user-land caching
private: isPreviewMode, // Leave to user-land caching
}
: undefined
)
Expand All @@ -946,25 +953,27 @@ export default class Server {
!this.renderOpts.dev
? {
revalidate: -1,
private: false, // Leave to user-land caching
private: isPreviewMode, // Leave to user-land caching
}
: undefined
)
return null
}

return renderToHTML(req, res, pathname, query, {
const html = await renderToHTML(req, res, pathname, query, {
...components,
...opts,
})
}

const previewData = tryGetPreviewData(
req,
res,
this.renderOpts.previewProps
)
const isPreviewMode = previewData !== false
if (html) {
sendPayload(res, html, 'text/html; charset=utf-8', {
revalidate: -1,
private: isPreviewMode,
})
}

return null
}

// Compute the SPR cache key
const urlPathname = parseUrl(req.url || '').pathname!
Expand Down
47 changes: 25 additions & 22 deletions packages/next/next-server/server/render.tsx
Expand Up @@ -465,12 +465,12 @@ export async function renderToHTML(
router,
ctx,
})
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData = tryGetPreviewData(req, res, previewProps)
ijjk marked this conversation as resolved.
Show resolved Hide resolved

if (isSpr && !isFallback) {
// Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless.
const previewData = tryGetPreviewData(req, res, previewProps)
const data = await getStaticProps!({
...(pageIsDynamic ? { params: query as ParsedUrlQuery } : undefined),
...(previewData !== false
Expand Down Expand Up @@ -523,31 +523,34 @@ export async function renderToHTML(
;(renderOpts as any).revalidate = data.revalidate
;(renderOpts as any).pageData = props
}

if (getServerSideProps && !isFallback) {
const data = await getServerSideProps({
req,
res,
query,
...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined),
...(previewData !== false
? { preview: true, previewData: previewData }
: undefined),
})

const invalidKeys = Object.keys(data).filter(key => key !== 'props')

if (invalidKeys.length) {
throw new Error(invalidKeysMsg('getServerSideProps', invalidKeys))
}

props.pageProps = data.props
;(renderOpts as any).pageData = props
}
} catch (err) {
if (!dev || !err) throw err
ctx.err = err
renderOpts.err = err
console.error(err)
}

if (getServerSideProps && !isFallback) {
const data = await getServerSideProps({
req,
res,
...(pageIsDynamic ? { params: params as ParsedUrlQuery } : undefined),
query,
})

const invalidKeys = Object.keys(data).filter(key => key !== 'props')

if (invalidKeys.length) {
throw new Error(invalidKeysMsg('getServerSideProps', invalidKeys))
}

props.pageProps = data.props
;(renderOpts as any).pageData = props
}

if (
!isSpr && // we only show this warning for legacy pages
!getServerSideProps &&
Expand Down
2 changes: 2 additions & 0 deletions packages/next/types/index.d.ts
Expand Up @@ -83,6 +83,8 @@ export type GetServerSideProps = (context: {
res: ServerResponse
params?: ParsedUrlQuery
query: ParsedUrlQuery
preview?: boolean
previewData?: any
}) => Promise<{ [key: string]: any }>

export default next
@@ -0,0 +1,4 @@
export default (req, res) => {
res.setPreviewData(req.query)
res.status(200).end()
}
@@ -0,0 +1,4 @@
export default (req, res) => {
res.clearPreviewData()
res.status(200).end()
}
15 changes: 15 additions & 0 deletions test/integration/getserversideprops-preview/pages/index.js
@@ -0,0 +1,15 @@
export function getServerSideProps({ preview, previewData }) {
return { props: { hasProps: true, preview, previewData } }
}

export default function({ hasProps, preview, previewData }) {
if (!hasProps) {
return <pre id="props-pre">Has No Props</pre>
}

return (
<pre id="props-pre">
{JSON.stringify(preview) + ' and ' + JSON.stringify(previewData)}
</pre>
)
}
41 changes: 41 additions & 0 deletions test/integration/getserversideprops-preview/server.js
@@ -0,0 +1,41 @@
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
const server = http.createServer((req, res) => {
let { pathname } = url.parse(req.url)
if (pathname.startsWith('/_next/data')) {
pathname = pathname
.replace(`/_next/data/${process.env.BUILD_ID}/`, '/')
.replace(/\.json$/, '')
}
console.log('serving', pathname)

if (pathname === '/favicon.ico') {
res.statusCode = 404
return res.end()
}

if (pathname.startsWith('/_next/static/')) {
res.write(
fs.readFileSync(
path.join(
__dirname,
'./.next/static/',
pathname.slice('/_next/static/'.length)
),
'utf8'
)
)
return res.end()
} else {
const re = require(`./.next/serverless/pages${pathname}`)
return typeof re.render === 'function'
? re.render(req, res)
: re.default(req, res)
}
})

server.listen(process.env.PORT, () => {
console.log('ready on', process.env.PORT)
})