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