Commit 2ae475e0 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

SPR follow ups (#8846)

* Add revalidate header and error when invalid
object from getStaticProps

* Make sprCache no-op in dev mode

* Update packages/next/next-server/server/next-server.ts

* Update tests for fixes

* Update getStaticProps error and add test

* Update manifest test

* Add validating revalidate value

* Apply suggestions from code review
Co-Authored-By: 's avatarJoe Haddad <joe.haddad@zeit.co>

* Change from error to warning high revalidate value
parent fd50e51e
......@@ -505,7 +505,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (isSpr) {
// For a non-dynamic SPR page, we must copy its data file from export.
if (!isDynamic) {
await moveExportedPage(page, page, true, 'json')
await moveExportedPage(page, file, true, 'json')
finalPrerenderRoutes[page] = {
initialRevalidateSeconds:
......
......@@ -292,6 +292,7 @@ export default async function (dir, options, configuration) {
if (!options.buildExport && prerenderManifest) {
await Promise.all(
Object.keys(prerenderManifest.routes).map(async route => {
route = route === '/' ? '/index' : route
const orig = join(distPagesDir, route)
const htmlDest = join(outDir, `${route}.html`)
const jsonDest = join(sprDataDir, `${route}.json`)
......
......@@ -520,10 +520,22 @@ export default class Server {
)
}
private __sendPayload(res: ServerResponse, payload: any, header: string) {
private __sendPayload(
res: ServerResponse,
payload: any,
type: string,
revalidate?: number | false
) {
// TODO: ETag? Cache-Control headers? Next-specific headers?
res.setHeader('Content-Type', header)
res.setHeader('Content-Type', type)
res.setHeader('Content-Length', Buffer.byteLength(payload))
if (revalidate) {
res.setHeader(
'Cache-Control',
`s-maxage=${revalidate}, stale-while-revalidate, stale-if-error`
)
}
res.end(payload)
}
......@@ -577,7 +589,8 @@ export default class Server {
this.__sendPayload(
res,
data,
isSprData ? 'application/json' : 'text/html; charset=utf-8'
isSprData ? 'application/json' : 'text/html; charset=utf-8',
cachedData.curRevalidate
)
// Stop the request chain here if the data we sent was up-to-date
......@@ -634,7 +647,8 @@ export default class Server {
this.__sendPayload(
res,
isSprData ? JSON.stringify(sprData) : html,
isSprData ? 'application/json' : 'text/html; charset=utf-8'
isSprData ? 'application/json' : 'text/html; charset=utf-8',
sprRevalidate
)
}
......
......@@ -379,6 +379,33 @@ export async function renderToHTML(
const data = await unstable_getStaticProps!({
params: isDynamicRoute(pathname) ? query : undefined,
})
const invalidKeys = Object.keys(data).filter(
key => key !== 'revalidate' && key !== 'props'
)
if (invalidKeys.length) {
throw new Error(
`Additional keys were returned from \`getStaticProps\`. Properties intended for your component must be nested under the \`props\` key, e.g.:\n\n\treturn { props: { title: 'My Title', content: '...' }\n\nKeys that need moved: ${invalidKeys.join(
', '
)}.
`
)
}
if (typeof data.revalidate === 'number') {
if (data.revalidate < 0) {
throw new Error(
`A page's revalidate option can not be less than zero. A revalidate option of zero means to revalidate _after_ every request. To never revalidate, you can set revalidate to \`false\` (only ran once at build-time).`
)
} else if (data.revalidate > 31536000) {
// if it's greater than a year for some reason error
console.warn(
`Warning: A page's revalidate option was set to more than a year. This may have been done in error.\nTo only run getStaticProps at build-time and not revalidate at runtime, you can set \`revalidate\` to \`false\`!`
)
}
}
props.pageProps = data.props
// pass up revalidate and props for export
;(renderOpts as any).revalidate = data.revalidate
......
......@@ -13,6 +13,7 @@ type SprCacheValue = {
html: string
pageData: any
isStale?: boolean
curRevalidate?: number | false
// milliseconds to revalidate after
revalidateAfter: number | false
}
......@@ -93,6 +94,7 @@ export function initializeSprCache({
export async function getSprCache(
pathname: string
): Promise<SprCacheValue | undefined> {
if (sprOptions.dev) return
pathname = normalizePagePath(pathname)
let data: SprCacheValue | undefined = cache.get(pathname)
......@@ -123,6 +125,11 @@ export async function getSprCache(
) {
data.isStale = true
}
const manifestEntry = prerenderManifest.routes[pathname]
if (data && manifestEntry) {
data.curRevalidate = manifestEntry.initialRevalidateSeconds
}
return data
}
......@@ -135,6 +142,7 @@ export async function setSprCache(
},
revalidateSeconds?: number | false
) {
if (sprOptions.dev) return
if (typeof revalidateSeconds !== 'undefined') {
prerenderManifest.routes[pathname] = {
initialRevalidateSeconds: revalidateSeconds,
......
import Link from 'next/link'
// eslint-disable-next-line camelcase
export async function unstable_getStaticProps () {
return {
props: { world: 'world', time: new Date().getTime() },
// bad-prop
revalidate: 1
}
}
const Page = ({ world, time }) => {
return (
<>
......@@ -28,6 +37,4 @@ const Page = ({ world, time }) => {
)
}
Page.getInitialProps = () => ({ world: 'world', time: new Date().getTime() })
export default Page
......@@ -116,12 +116,44 @@ const runTests = (dev = false) => {
expect(text).toMatch(/a normal page/)
})
if (!dev) {
if (dev) {
it('should always call getStaticProps without caching in dev', async () => {
const initialHtml = await renderViaHTTP(appPort, '/something')
expect(initialHtml).toMatch(/hello.*?world/)
const newHtml = await renderViaHTTP(appPort, '/something')
expect(newHtml).toMatch(/hello.*?world/)
expect(initialHtml !== newHtml).toBe(true)
const newerHtml = await renderViaHTTP(appPort, '/something')
expect(newerHtml).toMatch(/hello.*?world/)
expect(newHtml !== newerHtml).toBe(true)
})
it('should error on bad object from getStaticProps', async () => {
const indexPage = join(__dirname, '../pages/index.js')
const origContent = await fs.readFile(indexPage, 'utf8')
await fs.writeFile(
indexPage,
origContent.replace(/\/\/ bad-prop/, 'another: true,')
)
await waitFor(1000)
try {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Additional keys were returned/)
} finally {
await fs.writeFile(indexPage, origContent)
}
})
} else {
it('outputs a prerender-manifest correctly', async () => {
const manifest = require(join(appDir, '.next', 'prerender-manifest.json'))
expect(manifest.version).toBe(1)
expect(manifest.routes).toEqual({
'/': {
initialRevalidateSeconds: 1
},
'/blog/[post3]': {
initialRevalidateSeconds: 10
},
......
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