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> { ...@@ -505,7 +505,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (isSpr) { if (isSpr) {
// For a non-dynamic SPR page, we must copy its data file from export. // For a non-dynamic SPR page, we must copy its data file from export.
if (!isDynamic) { if (!isDynamic) {
await moveExportedPage(page, page, true, 'json') await moveExportedPage(page, file, true, 'json')
finalPrerenderRoutes[page] = { finalPrerenderRoutes[page] = {
initialRevalidateSeconds: initialRevalidateSeconds:
......
...@@ -292,6 +292,7 @@ export default async function (dir, options, configuration) { ...@@ -292,6 +292,7 @@ export default async function (dir, options, configuration) {
if (!options.buildExport && prerenderManifest) { if (!options.buildExport && prerenderManifest) {
await Promise.all( await Promise.all(
Object.keys(prerenderManifest.routes).map(async route => { Object.keys(prerenderManifest.routes).map(async route => {
route = route === '/' ? '/index' : route
const orig = join(distPagesDir, route) const orig = join(distPagesDir, route)
const htmlDest = join(outDir, `${route}.html`) const htmlDest = join(outDir, `${route}.html`)
const jsonDest = join(sprDataDir, `${route}.json`) const jsonDest = join(sprDataDir, `${route}.json`)
......
...@@ -520,10 +520,22 @@ export default class Server { ...@@ -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? // 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)) 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) res.end(payload)
} }
...@@ -577,7 +589,8 @@ export default class Server { ...@@ -577,7 +589,8 @@ export default class Server {
this.__sendPayload( this.__sendPayload(
res, res,
data, 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 // Stop the request chain here if the data we sent was up-to-date
...@@ -634,7 +647,8 @@ export default class Server { ...@@ -634,7 +647,8 @@ export default class Server {
this.__sendPayload( this.__sendPayload(
res, res,
isSprData ? JSON.stringify(sprData) : html, 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( ...@@ -379,6 +379,33 @@ export async function renderToHTML(
const data = await unstable_getStaticProps!({ const data = await unstable_getStaticProps!({
params: isDynamicRoute(pathname) ? query : undefined, 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 props.pageProps = data.props
// pass up revalidate and props for export // pass up revalidate and props for export
;(renderOpts as any).revalidate = data.revalidate ;(renderOpts as any).revalidate = data.revalidate
......
...@@ -13,6 +13,7 @@ type SprCacheValue = { ...@@ -13,6 +13,7 @@ type SprCacheValue = {
html: string html: string
pageData: any pageData: any
isStale?: boolean isStale?: boolean
curRevalidate?: number | false
// milliseconds to revalidate after // milliseconds to revalidate after
revalidateAfter: number | false revalidateAfter: number | false
} }
...@@ -93,6 +94,7 @@ export function initializeSprCache({ ...@@ -93,6 +94,7 @@ export function initializeSprCache({
export async function getSprCache( export async function getSprCache(
pathname: string pathname: string
): Promise<SprCacheValue | undefined> { ): Promise<SprCacheValue | undefined> {
if (sprOptions.dev) return
pathname = normalizePagePath(pathname) pathname = normalizePagePath(pathname)
let data: SprCacheValue | undefined = cache.get(pathname) let data: SprCacheValue | undefined = cache.get(pathname)
...@@ -123,6 +125,11 @@ export async function getSprCache( ...@@ -123,6 +125,11 @@ export async function getSprCache(
) { ) {
data.isStale = true data.isStale = true
} }
const manifestEntry = prerenderManifest.routes[pathname]
if (data && manifestEntry) {
data.curRevalidate = manifestEntry.initialRevalidateSeconds
}
return data return data
} }
...@@ -135,6 +142,7 @@ export async function setSprCache( ...@@ -135,6 +142,7 @@ export async function setSprCache(
}, },
revalidateSeconds?: number | false revalidateSeconds?: number | false
) { ) {
if (sprOptions.dev) return
if (typeof revalidateSeconds !== 'undefined') { if (typeof revalidateSeconds !== 'undefined') {
prerenderManifest.routes[pathname] = { prerenderManifest.routes[pathname] = {
initialRevalidateSeconds: revalidateSeconds, initialRevalidateSeconds: revalidateSeconds,
......
import Link from 'next/link' 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 }) => { const Page = ({ world, time }) => {
return ( return (
<> <>
...@@ -28,6 +37,4 @@ const Page = ({ world, time }) => { ...@@ -28,6 +37,4 @@ const Page = ({ world, time }) => {
) )
} }
Page.getInitialProps = () => ({ world: 'world', time: new Date().getTime() })
export default Page export default Page
...@@ -116,12 +116,44 @@ const runTests = (dev = false) => { ...@@ -116,12 +116,44 @@ const runTests = (dev = false) => {
expect(text).toMatch(/a normal page/) 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 () => { it('outputs a prerender-manifest correctly', async () => {
const manifest = require(join(appDir, '.next', 'prerender-manifest.json')) const manifest = require(join(appDir, '.next', 'prerender-manifest.json'))
expect(manifest.version).toBe(1) expect(manifest.version).toBe(1)
expect(manifest.routes).toEqual({ expect(manifest.routes).toEqual({
'/': {
initialRevalidateSeconds: 1
},
'/blog/[post3]': { '/blog/[post3]': {
initialRevalidateSeconds: 10 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