Unverified Commit 9793e900 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add isPreview field to router (#21638)

This adds an `isPreview` field to the `next/router` to allow detecting when in preview mode. 

Closes: https://github.com/vercel/next.js/issues/14903
parent 12cd2f9f
......@@ -50,6 +50,7 @@ The following is the definition of the `router` object returned by both [`useRou
- `locales`: `String[]` - All supported locales (if enabled).
- `defaultLocale`: `String` - The current default locale (if enabled).
- `isReady`: `boolean` - Whether the router fields are updated client-side and ready for use. Should only be used inside of `useEffect` methods and not for conditionally rendering on the server.
- `isPreview`: `boolean` - Whether the application is currently in [preview mode](/docs/advanced-features/preview-mode.md).
Additionally, the following methods are also included inside `router`:
......
......@@ -71,6 +71,7 @@ const {
locale,
locales,
domainLocales,
isPreview,
} = data
let { defaultLocale } = data
......@@ -375,6 +376,7 @@ export default async (opts: { webpackHMR?: any } = {}) => {
locales,
defaultLocale,
domainLocales,
isPreview,
})
// call init-client middleware
......
......@@ -41,6 +41,7 @@ const urlPropertyFields = [
'locales',
'defaultLocale',
'isReady',
'isPreview',
'isLocaleDomain',
]
const routerEvents = [
......
......@@ -363,6 +363,7 @@ export type NextRouter = BaseRouter &
| 'events'
| 'isFallback'
| 'isReady'
| 'isPreview'
>
export type PrefetchOptions = {
......@@ -489,6 +490,7 @@ export default class Router implements BaseRouter {
defaultLocale?: string
domainLocales?: DomainLocales
isReady: boolean
isPreview: boolean
isLocaleDomain: boolean
private _idx: number = 0
......@@ -512,6 +514,7 @@ export default class Router implements BaseRouter {
locales,
defaultLocale,
domainLocales,
isPreview,
}: {
subscription: Subscription
initialProps: any
......@@ -525,6 +528,7 @@ export default class Router implements BaseRouter {
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
isPreview?: boolean
}
) {
// represents the current component key
......@@ -581,6 +585,7 @@ export default class Router implements BaseRouter {
self.__NEXT_DATA__.gip ||
(!autoExportDynamic && !self.location.search)
)
this.isPreview = !!isPreview
this.isLocaleDomain = false
if (process.env.__NEXT_I18N_SUPPORT) {
......@@ -1069,6 +1074,8 @@ export default class Router implements BaseRouter {
return new Promise(() => {})
}
this.isPreview = !!props.__N_PREVIEW
// handle SSG data 404
if (props.notFound === SSG_DATA_NOT_FOUND) {
let notFoundRoute
......@@ -1539,7 +1546,11 @@ export default class Router implements BaseRouter {
_getStaticData(dataHref: string): Promise<object> {
const { href: cacheKey } = new URL(dataHref, window.location.href)
if (process.env.NODE_ENV === 'production' && this.sdc[cacheKey]) {
if (
process.env.NODE_ENV === 'production' &&
!this.isPreview &&
this.sdc[cacheKey]
) {
return Promise.resolve(this.sdc[cacheKey])
}
return fetchNextData(dataHref, this.isSsr).then((data) => {
......
......@@ -103,6 +103,7 @@ export type NEXT_DATA = {
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
isPreview?: boolean
}
/**
......
......@@ -80,6 +80,7 @@ class ServerRouter implements NextRouter {
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocales
isPreview: boolean
isLocaleDomain: boolean
// TODO: Remove in the next major version, as this would mean the user is adding event listeners in server-side `render` method
static events: MittEmitter = mitt()
......@@ -91,11 +92,12 @@ class ServerRouter implements NextRouter {
{ isFallback }: { isFallback: boolean },
isReady: boolean,
basePath: string,
locale: string | undefined,
locales: string[] | undefined,
defaultLocale: string | undefined,
domainLocales: DomainLocales | undefined,
isLocaleDomain: boolean
locale?: string,
locales?: string[],
defaultLocale?: string,
domainLocales?: DomainLocales,
isPreview?: boolean,
isLocaleDomain?: boolean
) {
this.route = pathname.replace(/\/$/, '') || '/'
this.pathname = pathname
......@@ -108,7 +110,8 @@ class ServerRouter implements NextRouter {
this.defaultLocale = defaultLocale
this.isReady = isReady
this.domainLocales = domainLocales
this.isLocaleDomain = isLocaleDomain
this.isPreview = !!isPreview
this.isLocaleDomain = !!isLocaleDomain
}
push(): any {
......@@ -233,6 +236,7 @@ function renderDocument(
locales,
defaultLocale,
domainLocales,
isPreview,
}: RenderOpts & {
props: any
docComponentsRendered: DocumentProps['docComponentsRendered']
......@@ -255,6 +259,7 @@ function renderDocument(
appGip?: boolean
devOnlyCacheBusterQueryString: string
scriptLoader: any
isPreview?: boolean
}
): string {
return (
......@@ -284,6 +289,7 @@ function renderDocument(
locales,
defaultLocale,
domainLocales,
isPreview,
},
buildManifest,
docComponentsRendered,
......@@ -538,6 +544,17 @@ export async function renderToHTML(
await Loadable.preloadAll() // Make sure all dynamic imports are loaded
let isPreview
let previewData: string | false | object | undefined
if ((isSSG || getServerSideProps) && !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.
previewData = tryGetPreviewData(req, res, previewProps)
isPreview = previewData !== false
}
// url will always be set
const asPath: string = renderOpts.resolvedAsPath || (req.url as string)
const routerIsReady = !!(getServerSideProps || hasPageGetInitialProps)
......@@ -554,6 +571,7 @@ export async function renderToHTML(
renderOpts.locales,
renderOpts.defaultLocale,
renderOpts.domainLocales,
isPreview,
(req as any).__nextIsLocaleDomain
)
const ctx = {
......@@ -620,17 +638,12 @@ export async function renderToHTML(
ctx,
})
if (isSSG) {
props[STATIC_PROPS_ID] = true
if ((isSSG || getServerSideProps) && isPreview) {
props.__N_PREVIEW = true
}
let previewData: string | false | object | undefined
if ((isSSG || getServerSideProps) && !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.
previewData = tryGetPreviewData(req, res, previewProps)
if (isSSG) {
props[STATIC_PROPS_ID] = true
}
if (isSSG && !isFallback) {
......@@ -639,7 +652,7 @@ export async function renderToHTML(
try {
data = await getStaticProps!({
...(pageIsDynamic ? { params: query as ParsedUrlQuery } : undefined),
...(previewData !== false
...(isPreview
? { preview: true, previewData: previewData }
: undefined),
locales: renderOpts.locales,
......@@ -788,6 +801,7 @@ export async function renderToHTML(
props.pageProps,
'props' in data ? data.props : undefined
)
// pass up revalidate and props for export
// TODO: change this to a different passing mechanism
;(renderOpts as any).revalidate =
......@@ -1052,6 +1066,7 @@ export async function renderToHTML(
appGip: !defaultAppGetInitialProps ? true : undefined,
devOnlyCacheBusterQueryString,
scriptLoader,
isPreview: isPreview === true ? true : undefined,
})
if (process.env.NODE_ENV !== 'production') {
......
......@@ -104,7 +104,7 @@ describe('Build Output', () => {
expect(parseFloat(err404FirstLoad)).toBeCloseTo(67.1, 0)
expect(err404FirstLoad.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll)).toBeCloseTo(63.6, 1)
expect(parseFloat(sharedByAll)).toBeCloseTo(63.7, 1)
expect(sharedByAll.endsWith('kB')).toBe(true)
if (_appSize.endsWith('kB')) {
......@@ -168,7 +168,7 @@ describe('Build Output', () => {
expect(parseFloat(indexSize)).toBeGreaterThanOrEqual(2)
expect(indexSize.endsWith('kB')).toBe(true)
expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(66.6)
expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(66.7)
expect(parseFloat(indexFirstLoad)).toBeGreaterThanOrEqual(60)
expect(indexFirstLoad.endsWith('kB')).toBe(true)
})
......
import { useRouter } from 'next/router'
export function getServerSideProps({ res, preview, previewData }) {
// test override in preview mode
res.setHeader('Cache-Control', 'public, max-age=3600')
......@@ -11,13 +13,14 @@ export function getServerSideProps({ res, 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>
<>
<pre id="props-pre">
{hasProps
? JSON.stringify(preview) + ' and ' + JSON.stringify(previewData)
: 'Has No Props'}
</pre>
<p id="router">{JSON.stringify(useRouter())}</p>
</>
)
}
......@@ -30,7 +30,12 @@ function getData(html) {
const $ = cheerio.load(html)
const nextData = $('#__NEXT_DATA__')
const preEl = $('#props-pre')
return { nextData: JSON.parse(nextData.html()), pre: preEl.text() }
const routerData = JSON.parse($('#router').text())
return {
nextData: JSON.parse(nextData.html()),
pre: preEl.text(),
routerData,
}
}
function runTests(startServer = nextStart) {
......@@ -51,16 +56,20 @@ function runTests(startServer = nextStart) {
it('should return page on first request', async () => {
const html = await renderViaHTTP(appPort, '/')
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData.isPreview).toBeUndefined()
expect(pre).toBe('false and null')
expect(routerData.isPreview).toBe(false)
})
it('should return page on second request', async () => {
const html = await renderViaHTTP(appPort, '/')
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData.isPreview).toBeUndefined()
expect(pre).toBe('false and null')
expect(routerData.isPreview).toBe(false)
})
let previewCookieString
......@@ -96,12 +105,13 @@ function runTests(startServer = nextStart) {
)
const html = await res.text()
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(res.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData).toMatchObject({ isFallback: false, isPreview: true })
expect(pre).toBe('true and {"lets":"goooo"}')
expect(routerData.isPreview).toBe(true)
})
it('should return correct caching headers for data preview request', async () => {
......
import { useRouter } from 'next/router'
export function getStaticProps({ preview, previewData }) {
return {
props: {
......@@ -9,13 +11,14 @@ export function getStaticProps({ 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>
<>
<pre id="props-pre">
{hasProps
? JSON.stringify(preview) + ' and ' + JSON.stringify(previewData)
: 'Has No Props'}
</pre>
<p id="router">{JSON.stringify(useRouter())}</p>
</>
)
}
......@@ -30,7 +30,12 @@ function getData(html) {
const $ = cheerio.load(html)
const nextData = $('#__NEXT_DATA__')
const preEl = $('#props-pre')
return { nextData: JSON.parse(nextData.html()), pre: preEl.text() }
const routerData = JSON.parse($('#router').text())
return {
nextData: JSON.parse(nextData.html()),
pre: preEl.text(),
routerData,
}
}
function runTests(startServer = nextStart) {
......@@ -51,16 +56,20 @@ function runTests(startServer = nextStart) {
it('should return prerendered page on first request', async () => {
const html = await renderViaHTTP(appPort, '/')
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData.isPreview).toBeUndefined()
expect(pre).toBe('false and null')
expect(routerData.isPreview).toBe(false)
})
it('should return prerendered page on second request', async () => {
const html = await renderViaHTTP(appPort, '/')
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData.isPreview).toBeUndefined()
expect(pre).toBe('false and null')
expect(routerData.isPreview).toBe(false)
})
it('should throw error when setting too large of preview data', async () => {
......@@ -122,12 +131,13 @@ function runTests(startServer = nextStart) {
)
const html = await res.text()
const { nextData, pre } = getData(html)
const { nextData, pre, routerData } = getData(html)
expect(res.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
expect(nextData).toMatchObject({ isFallback: false })
expect(nextData).toMatchObject({ isFallback: false, isPreview: true })
expect(pre).toBe('true and {"lets":"goooo"}')
expect(routerData.isPreview).toBe(true)
})
it('should return correct caching headers for data preview request', async () => {
......
......@@ -20,6 +20,7 @@ export default function HelloPage(): JSX.Element {
console.log(process.browser)
console.log(router.pathname)
console.log(router.isReady)
console.log(router.isPreview)
return (
<div>
<p>One trillion dollars: {1_000_000_000_000}</p>
......
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