Unverified Commit 58e5c780 authored by Steven's avatar Steven Committed by GitHub

feat: add draft mode to `next/headers` (#48789)


fix NEXT-1003
Co-authored-by: 's avatarWyatt Johnson <633002+wyattjoh@users.noreply.github.com>
parent d23b1601
...@@ -36,6 +36,15 @@ startHandler(async ({ request, response, query, params, path }) => { ...@@ -36,6 +36,15 @@ startHandler(async ({ request, response, query, params, path }) => {
const context: RouteHandlerManagerContext = { const context: RouteHandlerManagerContext = {
params, params,
prerenderManifest: {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any,
},
staticGenerationContext: { staticGenerationContext: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
}, },
......
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/compiled/jsonwebtoken/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
},
start: SourcePos {
line: 10,
column: 1097,
},
end: SourcePos {
line: 10,
column: 1114,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"crypto\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"crypto\"\nPath where resolving has started: [project]/packages/next/dist/compiled/jsonwebtoken/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/jsonwebtoken/index.js",
},
start: SourcePos {
line: 10,
column: 978,
},
end: SourcePos {
line: 10,
column: 995,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/api-utils/node.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/server/api-utils/node.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/api-utils/node.js",
},
start: SourcePos {
line: 30,
column: 17,
},
end: SourcePos {
line: 30,
column: 34,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/crypto-utils.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"crypto\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"crypto\"\nPath where resolving has started: [project]/packages/next/dist/server/crypto-utils.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/crypto-utils.js",
},
start: SourcePos {
line: 22,
column: 56,
},
end: SourcePos {
line: 22,
column: 73,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/api-utils/node.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"querystring\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"querystring\"\nPath where resolving has started: [project]/packages/next/dist/server/api-utils/node.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/api-utils/node.js",
},
start: SourcePos {
line: 154,
column: 20,
},
end: SourcePos {
line: 154,
column: 42,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/raw-body/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/compiled/raw-body/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/raw-body/index.js",
},
start: SourcePos {
line: 50,
column: 702,
},
end: SourcePos {
line: 50,
column: 719,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/server/lib/mock-request.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"stream\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"stream\"\nPath where resolving has started: [project]/packages/next/dist/server/lib/mock-request.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/server/lib/mock-request.js",
},
start: SourcePos {
line: 26,
column: 56,
},
end: SourcePos {
line: 26,
column: 73,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
PlainIssue {
severity: Error,
context: "[project]/packages/next/dist/compiled/raw-body/index.js",
category: "resolve",
title: "Error resolving commonjs request",
description: "unable to resolve module \"path\"",
detail: "It was not possible to find the requested file.\nParsed request as written in source code: module \"path\"\nPath where resolving has started: [project]/packages/next/dist/compiled/raw-body/index.js\nType of request: commonjs request\nImport map: No import map entry\n",
documentation_link: "",
source: Some(
PlainIssueSource {
asset: PlainAsset {
ident: "[project]/packages/next/dist/compiled/raw-body/index.js",
},
start: SourcePos {
line: 50,
column: 654,
},
end: SourcePos {
line: 50,
column: 669,
},
},
),
sub_issues: [],
processing_path: Some(
[
PlainIssueProcessingPathItem {
context: Some(
"[project]/packages/next-swc/crates/next-dev-tests/tests/integration/next/app/route/input/app",
),
description: "Next.js App Route /[slug]",
},
],
),
}
\ No newline at end of file
...@@ -2833,6 +2833,11 @@ export default async function build( ...@@ -2833,6 +2833,11 @@ export default async function build(
JSON.stringify(prerenderManifest), JSON.stringify(prerenderManifest),
'utf8' 'utf8'
) )
await promises.writeFile(
path.join(distDir, PRERENDER_MANIFEST).replace(/\.json$/, '.js'),
`self.__PRERENDER_MANIFEST=${JSON.stringify(prerenderManifest)}`,
'utf8'
)
await generateClientSsgManifest(prerenderManifest, { await generateClientSsgManifest(prerenderManifest, {
distDir, distDir,
buildId, buildId,
...@@ -2851,6 +2856,11 @@ export default async function build( ...@@ -2851,6 +2856,11 @@ export default async function build(
JSON.stringify(prerenderManifest), JSON.stringify(prerenderManifest),
'utf8' 'utf8'
) )
await promises.writeFile(
path.join(distDir, PRERENDER_MANIFEST).replace(/\.json$/, '.js'),
`self.__PRERENDER_MANIFEST=${JSON.stringify(prerenderManifest)}`,
'utf8'
)
} }
const images = { ...config.images } const images = { ...config.images }
......
...@@ -134,6 +134,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -134,6 +134,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
} }
const buildManifest = self.__BUILD_MANIFEST const buildManifest = self.__BUILD_MANIFEST
const prerenderManifest = self.__PRERENDER_MANIFEST
const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST const reactLoadableManifest = self.__REACT_LOADABLE_MANIFEST
const rscManifest = self.__RSC_MANIFEST const rscManifest = self.__RSC_MANIFEST
const rscCssManifest = self.__RSC_CSS_MANIFEST const rscCssManifest = self.__RSC_CSS_MANIFEST
...@@ -153,6 +154,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> = ...@@ -153,6 +154,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
error500Mod, error500Mod,
Document, Document,
buildManifest, buildManifest,
prerenderManifest,
appRenderToHTML, appRenderToHTML,
pagesRenderToHTML, pagesRenderToHTML,
reactLoadableManifest, reactLoadableManifest,
......
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
WebNextResponse, WebNextResponse,
} from '../../../../server/base-http/web' } from '../../../../server/base-http/web'
import { SERVER_RUNTIME } from '../../../../lib/constants' import { SERVER_RUNTIME } from '../../../../lib/constants'
import { PrerenderManifest } from '../../..'
export function getRender({ export function getRender({
dev, dev,
...@@ -23,6 +24,7 @@ export function getRender({ ...@@ -23,6 +24,7 @@ export function getRender({
pagesType, pagesType,
Document, Document,
buildManifest, buildManifest,
prerenderManifest,
reactLoadableManifest, reactLoadableManifest,
appRenderToHTML, appRenderToHTML,
pagesRenderToHTML, pagesRenderToHTML,
...@@ -46,6 +48,7 @@ export function getRender({ ...@@ -46,6 +48,7 @@ export function getRender({
pagesRenderToHTML: any pagesRenderToHTML: any
Document: DocumentType Document: DocumentType
buildManifest: BuildManifest buildManifest: BuildManifest
prerenderManifest: PrerenderManifest
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
subresourceIntegrityManifest?: Record<string, string> subresourceIntegrityManifest?: Record<string, string>
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
...@@ -61,6 +64,7 @@ export function getRender({ ...@@ -61,6 +64,7 @@ export function getRender({
const baseLoadComponentResult = { const baseLoadComponentResult = {
dev, dev,
buildManifest, buildManifest,
prerenderManifest,
reactLoadableManifest, reactLoadableManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
nextFontManifest, nextFontManifest,
...@@ -75,6 +79,7 @@ export function getRender({ ...@@ -75,6 +79,7 @@ export function getRender({
webServerConfig: { webServerConfig: {
page, page,
pagesType, pagesType,
prerenderManifest,
extendRenderOpts: { extendRenderOpts: {
buildId, buildId,
runtime: SERVER_RUNTIME.experimentalEdge, runtime: SERVER_RUNTIME.experimentalEdge,
......
...@@ -7,6 +7,7 @@ import { RequestCookies } from '../../server/web/spec-extension/cookies' ...@@ -7,6 +7,7 @@ import { RequestCookies } from '../../server/web/spec-extension/cookies'
import { requestAsyncStorage } from './request-async-storage' import { requestAsyncStorage } from './request-async-storage'
import { actionAsyncStorage } from './action-async-storage' import { actionAsyncStorage } from './action-async-storage'
import { staticGenerationBailout } from './static-generation-bailout' import { staticGenerationBailout } from './static-generation-bailout'
import { DraftMode } from '../../../types'
export function headers() { export function headers() {
if (staticGenerationBailout('headers')) { if (staticGenerationBailout('headers')) {
...@@ -23,17 +24,6 @@ export function headers() { ...@@ -23,17 +24,6 @@ export function headers() {
return requestStore.headers return requestStore.headers
} }
export function previewData() {
const requestStore = requestAsyncStorage.getStore()
if (!requestStore) {
throw new Error(
`Invariant: Method expects to have requestAsyncStorage, none available`
)
}
return requestStore.previewData
}
export function cookies() { export function cookies() {
if (staticGenerationBailout('cookies')) { if (staticGenerationBailout('cookies')) {
return RequestCookiesAdapter.seal(new RequestCookies(new Headers({}))) return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))
...@@ -58,3 +48,29 @@ export function cookies() { ...@@ -58,3 +48,29 @@ export function cookies() {
return requestStore.cookies return requestStore.cookies
} }
export function draftMode(): DraftMode {
const requestStore = requestAsyncStorage.getStore()
if (!requestStore) {
throw new Error(
`Invariant: Method expects to have requestAsyncStorage, none available`
)
}
return {
get enabled() {
return requestStore.draftMode.enabled
},
enable() {
if (staticGenerationBailout('draftMode().enable()')) {
return
}
return requestStore.draftMode.enable()
},
disable() {
if (staticGenerationBailout('draftMode().disable()')) {
return
}
return requestStore.draftMode.disable()
},
}
}
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import type { ResponseCookies } from '../../server/web/spec-extension/cookies' import type { ResponseCookies } from '../../server/web/spec-extension/cookies'
import type { PreviewData } from '../../../types' import type { DraftMode } from '../../../types'
import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers' import type { ReadonlyHeaders } from '../../server/web/spec-extension/adapters/headers'
import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies' import type { ReadonlyRequestCookies } from '../../server/web/spec-extension/adapters/request-cookies'
...@@ -10,7 +10,7 @@ export interface RequestStore { ...@@ -10,7 +10,7 @@ export interface RequestStore {
readonly headers: ReadonlyHeaders readonly headers: ReadonlyHeaders
readonly cookies: ReadonlyRequestCookies readonly cookies: ReadonlyRequestCookies
readonly mutableCookies: ResponseCookies readonly mutableCookies: ResponseCookies
readonly previewData: PreviewData readonly draftMode: DraftMode
} }
export type RequestAsyncStorage = AsyncLocalStorage<RequestStore> export type RequestAsyncStorage = AsyncLocalStorage<RequestStore>
......
...@@ -388,6 +388,17 @@ export default async function exportPage({ ...@@ -388,6 +388,17 @@ export default async function exportPage({
// the route and the context for the request. // the route and the context for the request.
const context: AppRouteRouteHandlerContext = { const context: AppRouteRouteHandlerContext = {
params, params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: '',
},
notFoundRoutes: [],
},
staticGenerationContext: { staticGenerationContext: {
nextExport: true, nextExport: true,
supportsDynamicHTML: false, supportsDynamicHTML: false,
......
import type { IncomingMessage } from 'http'
import type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'
import type { ResponseCookies } from '../web/spec-extension/cookies'
import type { BaseNextRequest } from '../base-http'
import type { NextRequest } from '../web/spec-extension/request'
import {
COOKIE_NAME_PRERENDER_BYPASS,
checkIsOnDemandRevalidate,
__ApiPreviewProps,
} from '../api-utils'
export class DraftMode {
public readonly enabled: boolean
private readonly previewModeId: string | undefined
constructor(
previewProps: __ApiPreviewProps | undefined,
req: IncomingMessage | BaseNextRequest<unknown> | NextRequest,
private readonly cookies: ReadonlyRequestCookies,
private readonly mutableCookies: ResponseCookies
) {
// The logic for draftMode() is very similar to tryGetPreviewData()
// but Draft Mode does not have any data associated with it.
const isOnDemandRevalidate =
previewProps &&
checkIsOnDemandRevalidate(req, previewProps).isOnDemandRevalidate
const cookieValue = this.cookies.get(COOKIE_NAME_PRERENDER_BYPASS)?.value
this.enabled = Boolean(
!isOnDemandRevalidate &&
cookieValue &&
previewProps &&
cookieValue === previewProps.previewModeId
)
this.previewModeId = previewProps?.previewModeId
}
enable() {
if (!this.previewModeId) {
throw new Error(
'Invariant: previewProps missing previewModeId this should not be hit'
)
}
this.mutableCookies.set({
name: COOKIE_NAME_PRERENDER_BYPASS,
value: this.previewModeId,
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
})
}
disable() {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
this.mutableCookies.set({
name: COOKIE_NAME_PRERENDER_BYPASS,
value: '',
httpOnly: true,
sameSite: process.env.NODE_ENV !== 'development' ? 'none' : 'lax',
secure: process.env.NODE_ENV !== 'development',
path: '/',
expires: new Date(0),
})
}
}
import type { tryGetPreviewData as TryGetPreviewData } from '../api-utils/node'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http' import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'http'
import type { AsyncLocalStorage } from 'async_hooks' import type { AsyncLocalStorage } from 'async_hooks'
import type { PreviewData } from '../../../types'
import type { RequestStore } from '../../client/components/request-async-storage' import type { RequestStore } from '../../client/components/request-async-storage'
import type { RenderOpts } from '../app-render/types' import type { RenderOpts } from '../app-render/types'
import type { AsyncStorageWrapper } from './async-storage-wrapper' import type { AsyncStorageWrapper } from './async-storage-wrapper'
...@@ -19,6 +17,8 @@ import { ...@@ -19,6 +17,8 @@ import {
type ReadonlyRequestCookies, type ReadonlyRequestCookies,
} from '../web/spec-extension/adapters/request-cookies' } from '../web/spec-extension/adapters/request-cookies'
import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies' import { RequestCookies, ResponseCookies } from '../web/spec-extension/cookies'
import { __ApiPreviewProps } from '../api-utils'
import { DraftMode } from './draft-mode'
function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders { function getHeaders(headers: Headers | IncomingHttpHeaders): ReadonlyHeaders {
const cleaned = HeadersAdapter.from(headers) const cleaned = HeadersAdapter.from(headers)
...@@ -44,15 +44,6 @@ function getMutableCookies( ...@@ -44,15 +44,6 @@ function getMutableCookies(
return MutableRequestCookiesAdapter.seal(cookies, res) return MutableRequestCookiesAdapter.seal(cookies, res)
} }
/**
* Tries to get the preview data on the request for the given route. This
* isn't enabled in the edge runtime yet.
*/
const tryGetPreviewData: typeof TryGetPreviewData | null =
process.env.NEXT_RUNTIME !== 'edge'
? require('../api-utils/node').tryGetPreviewData
: null
export type RequestContext = { export type RequestContext = {
req: IncomingMessage | BaseNextRequest | NextRequest req: IncomingMessage | BaseNextRequest | NextRequest
res?: ServerResponse | BaseNextResponse res?: ServerResponse | BaseNextResponse
...@@ -77,19 +68,18 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -77,19 +68,18 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
{ req, res, renderOpts }: RequestContext, { req, res, renderOpts }: RequestContext,
callback: (store: RequestStore) => Result callback: (store: RequestStore) => Result
): Result { ): Result {
// Reads of this are cached on the `req` object, so this should resolve let previewProps: __ApiPreviewProps | undefined = undefined
// instantly. There's no need to pass this data down from a previous
// invoke. if (renderOpts && 'previewProps' in renderOpts) {
const previewData: PreviewData = // TODO: investigate why previewProps isn't on RenderOpts
renderOpts && tryGetPreviewData && res previewProps = (renderOpts as any).previewProps
? // TODO: investigate why previewProps isn't on RenderOpts }
tryGetPreviewData(req, res, (renderOpts as any).previewProps)
: false
const cache: { const cache: {
headers?: ReadonlyHeaders headers?: ReadonlyHeaders
cookies?: ReadonlyRequestCookies cookies?: ReadonlyRequestCookies
mutableCookies?: ResponseCookies mutableCookies?: ResponseCookies
draftMode?: DraftMode
} = {} } = {}
const store: RequestStore = { const store: RequestStore = {
...@@ -117,7 +107,18 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper< ...@@ -117,7 +107,18 @@ export const RequestAsyncStorageWrapper: AsyncStorageWrapper<
} }
return cache.mutableCookies return cache.mutableCookies
}, },
previewData, get draftMode() {
if (!cache.draftMode) {
cache.draftMode = new DraftMode(
previewProps,
req,
this.cookies,
this.mutableCookies
)
}
return cache.draftMode
},
} }
return storage.run(store, callback, store) return storage.run(store, callback, store)
......
...@@ -419,7 +419,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -419,7 +419,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
canonicalBase: this.nextConfig.amp.canonicalBase || '', canonicalBase: this.nextConfig.amp.canonicalBase || '',
buildId: this.buildId, buildId: this.buildId,
generateEtags, generateEtags,
previewProps: this.getPreviewProps(), previewProps: this.getPrerenderManifest().preview,
customServer: customServer === true ? true : undefined, customServer: customServer === true ? true : undefined,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer, ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath, basePath: this.nextConfig.basePath,
...@@ -1007,10 +1007,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1007,10 +1007,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Backwards compatibility // Backwards compatibility
protected async close(): Promise<void> {} protected async close(): Promise<void> {}
protected getPreviewProps(): __ApiPreviewProps {
return this.getPrerenderManifest().preview
}
protected async _beforeCatchAllRender( protected async _beforeCatchAllRender(
_req: BaseNextRequest, _req: BaseNextRequest,
_res: BaseNextResponse, _res: BaseNextResponse,
...@@ -1605,6 +1601,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1605,6 +1601,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (match) { if (match) {
const context: RouteHandlerManagerContext = { const context: RouteHandlerManagerContext = {
params: match.params, params: match.params,
prerenderManifest: this.getPrerenderManifest(),
staticGenerationContext: { staticGenerationContext: {
supportsDynamicHTML, supportsDynamicHTML,
incrementalCache, incrementalCache,
......
import type { __ApiPreviewProps } from '../api-utils'
import type { CustomRoutes } from '../../lib/load-custom-routes' import type { CustomRoutes } from '../../lib/load-custom-routes'
import type { FindComponentsResult } from '../next-server' import type { FindComponentsResult } from '../next-server'
import type { LoadComponentsReturnType } from '../load-components' import type { LoadComponentsReturnType } from '../load-components'
...@@ -14,7 +13,6 @@ import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-inf ...@@ -14,7 +13,6 @@ import type { MiddlewareMatcher } from '../../build/analysis/get-page-static-inf
import type { FunctionComponent } from 'react' import type { FunctionComponent } from 'react'
import type { RouteMatch } from '../future/route-matches/route-match' import type { RouteMatch } from '../future/route-matches/route-match'
import crypto from 'crypto'
import fs from 'fs' import fs from 'fs'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
...@@ -917,7 +915,7 @@ export default class DevServer extends Server { ...@@ -917,7 +915,7 @@ export default class DevServer extends Server {
pagesDir: this.pagesDir, pagesDir: this.pagesDir,
distDir: this.distDir, distDir: this.distDir,
config: this.nextConfig, config: this.nextConfig,
previewProps: this.getPreviewProps(), previewProps: this.getPrerenderManifest().preview,
buildId: this.buildId, buildId: this.buildId,
rewrites, rewrites,
appDir: this.appDir, appDir: this.appDir,
...@@ -1427,18 +1425,6 @@ export default class DevServer extends Server { ...@@ -1427,18 +1425,6 @@ export default class DevServer extends Server {
} }
} }
private _devCachedPreviewProps: __ApiPreviewProps | undefined
protected getPreviewProps() {
if (this._devCachedPreviewProps) {
return this._devCachedPreviewProps
}
return (this._devCachedPreviewProps = {
previewModeId: crypto.randomBytes(16).toString('hex'),
previewModeSigningKey: crypto.randomBytes(32).toString('hex'),
previewModeEncryptionKey: crypto.randomBytes(32).toString('hex'),
})
}
protected getPagesManifest(): PagesManifest | undefined { protected getPagesManifest(): PagesManifest | undefined {
return ( return (
NodeManifestLoader.require( NodeManifestLoader.require(
......
...@@ -34,6 +34,7 @@ import { getNonStaticMethods } from './helpers/get-non-static-methods' ...@@ -34,6 +34,7 @@ import { getNonStaticMethods } from './helpers/get-non-static-methods'
import { SYMBOL_MODIFY_COOKIE_VALUES } from '../../../web/spec-extension/adapters/request-cookies' import { SYMBOL_MODIFY_COOKIE_VALUES } from '../../../web/spec-extension/adapters/request-cookies'
import { ResponseCookies } from '../../../web/spec-extension/cookies' import { ResponseCookies } from '../../../web/spec-extension/cookies'
import { HeadersAdapter } from '../../../web/spec-extension/adapters/headers' import { HeadersAdapter } from '../../../web/spec-extension/adapters/headers'
import { PrerenderManifest } from '../../../../build'
/** /**
* AppRouteRouteHandlerContext is the context that is passed to the route * AppRouteRouteHandlerContext is the context that is passed to the route
...@@ -41,6 +42,7 @@ import { HeadersAdapter } from '../../../web/spec-extension/adapters/headers' ...@@ -41,6 +42,7 @@ import { HeadersAdapter } from '../../../web/spec-extension/adapters/headers'
*/ */
export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext { export interface AppRouteRouteHandlerContext extends RouteModuleHandleContext {
staticGenerationContext: StaticGenerationContext['renderOpts'] staticGenerationContext: StaticGenerationContext['renderOpts']
prerenderManifest: PrerenderManifest
} }
/** /**
...@@ -235,6 +237,11 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -235,6 +237,11 @@ export class AppRouteRouteModule extends RouteModule<
req: request, req: request,
} }
// TODO: types for renderOpts should include previewProps
;(requestContext as any).renderOpts = {
previewProps: context.prerenderManifest.preview,
}
// Get the context for the static generation. // Get the context for the static generation.
const staticGenerationContext: StaticGenerationContext = { const staticGenerationContext: StaticGenerationContext = {
pathname: this.definition.pathname, pathname: this.definition.pathname,
......
...@@ -47,6 +47,7 @@ import { ...@@ -47,6 +47,7 @@ import {
FLIGHT_SERVER_CSS_MANIFEST, FLIGHT_SERVER_CSS_MANIFEST,
SERVER_DIRECTORY, SERVER_DIRECTORY,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync' import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { findDir } from '../lib/find-pages-dir' import { findDir } from '../lib/find-pages-dir'
...@@ -402,21 +403,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -402,21 +403,7 @@ export default class NextNodeServer extends BaseServer {
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize, maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
flushToDisk: flushToDisk:
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => { getPrerenderManifest: () => this.getPrerenderManifest(),
if (dev) {
return {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any, // `preview` is special case read in next-dev-server
}
} else {
return this.getPrerenderManifest()
}
},
CurCacheHandler: CacheHandler, CurCacheHandler: CacheHandler,
}) })
} }
...@@ -2551,6 +2538,30 @@ export default class NextNodeServer extends BaseServer { ...@@ -2551,6 +2538,30 @@ export default class NextNodeServer extends BaseServer {
if (this._cachedPreviewManifest) { if (this._cachedPreviewManifest) {
return this._cachedPreviewManifest return this._cachedPreviewManifest
} }
if (
this.renderOpts?.dev ||
this.serverOptions?.dev ||
this.renderWorkerOpts?.dev ||
process.env.NODE_ENV === 'development' ||
process.env.NEXT_PHASE === PHASE_PRODUCTION_BUILD
) {
this._cachedPreviewManifest = {
version: 4,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: require('crypto').randomBytes(16).toString('hex'),
previewModeSigningKey: require('crypto')
.randomBytes(32)
.toString('hex'),
previewModeEncryptionKey: require('crypto')
.randomBytes(32)
.toString('hex'),
},
}
return this._cachedPreviewManifest
}
const manifest = require(join(this.distDir, PRERENDER_MANIFEST)) const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
return (this._cachedPreviewManifest = manifest) return (this._cachedPreviewManifest = manifest)
} }
......
...@@ -23,6 +23,8 @@ import { isDynamicRoute } from '../shared/lib/router/utils' ...@@ -23,6 +23,8 @@ import { isDynamicRoute } from '../shared/lib/router/utils'
import { interpolateDynamicPath, normalizeVercelUrl } from './server-utils' import { interpolateDynamicPath, normalizeVercelUrl } from './server-utils'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { IncrementalCache } from './lib/incremental-cache' import { IncrementalCache } from './lib/incremental-cache'
import { PrerenderManifest } from '../build'
interface WebServerOptions extends Options { interface WebServerOptions extends Options {
webServerConfig: { webServerConfig: {
page: string page: string
...@@ -35,6 +37,7 @@ interface WebServerOptions extends Options { ...@@ -35,6 +37,7 @@ interface WebServerOptions extends Options {
pagesRenderToHTML?: typeof import('./render').renderToHTML pagesRenderToHTML?: typeof import('./render').renderToHTML
appRenderToHTML?: typeof import('./app-render/app-render').renderToHTMLOrFlight appRenderToHTML?: typeof import('./app-render/app-render').renderToHTMLOrFlight
incrementalCacheHandler?: any incrementalCacheHandler?: any
prerenderManifest: PrerenderManifest | undefined
} }
} }
...@@ -73,21 +76,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -73,21 +76,7 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
flushToDisk: false, flushToDisk: false,
CurCacheHandler: CurCacheHandler:
this.serverOptions.webServerConfig.incrementalCacheHandler, this.serverOptions.webServerConfig.incrementalCacheHandler,
getPrerenderManifest: () => { getPrerenderManifest: () => this.getPrerenderManifest(),
if (dev) {
return {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any, // `preview` is special case read in next-dev-server
}
} else {
return this.getPrerenderManifest()
}
},
}) })
} }
protected getResponseCache() { protected getResponseCache() {
...@@ -157,17 +146,19 @@ export default class NextWebServer extends BaseServer<WebServerOptions> { ...@@ -157,17 +146,19 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query }) addRequestMeta(req, '__NEXT_INIT_QUERY', { ...parsedUrl.query })
} }
protected getPrerenderManifest() { protected getPrerenderManifest() {
return { const { prerenderManifest } = this.serverOptions.webServerConfig
version: 4 as const, if (this.renderOpts?.dev || !prerenderManifest) {
routes: {}, return {
dynamicRoutes: {}, version: -1 as any, // letting us know this doesn't conform to spec
notFoundRoutes: [], routes: {},
preview: { dynamicRoutes: {},
previewModeId: '', notFoundRoutes: [],
previewModeSigningKey: '', preview: {
previewModeEncryptionKey: '', previewModeId: 'development-id',
}, } as any, // `preview` is special case read in next-dev-server
}
} }
return prerenderManifest
} }
protected getServerComponentManifest() { protected getServerComponentManifest() {
return this.serverOptions.webServerConfig.extendRenderOpts return this.serverOptions.webServerConfig.extendRenderOpts
......
...@@ -82,6 +82,17 @@ export class EdgeRouteModuleWrapper { ...@@ -82,6 +82,17 @@ export class EdgeRouteModuleWrapper {
// match (if any). // match (if any).
const context: RouteHandlerManagerContext = { const context: RouteHandlerManagerContext = {
params: match.params, params: match.params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: {
previewModeEncryptionKey: '',
previewModeId: '',
previewModeSigningKey: '',
},
notFoundRoutes: [],
},
staticGenerationContext: { staticGenerationContext: {
supportsDynamicHTML: true, supportsDynamicHTML: true,
}, },
......
...@@ -141,6 +141,22 @@ export { ...@@ -141,6 +141,22 @@ export {
export type PreviewData = string | false | object | undefined export type PreviewData = string | false | object | undefined
export type DraftMode = {
/**
* Get the current value of Draft Mode.
* True when enabled, false when disabled.
*/
enabled: boolean
/**
* Set the value of Draft Mode to true.
*/
enable: () => void
/**
* Set the value of Draft Mode to false.
*/
disable: () => void
}
/** /**
* Context object passed into `getStaticProps`. * Context object passed into `getStaticProps`.
* @link https://nextjs.org/docs/api-reference/data-fetching/get-static-props#context-parameter * @link https://nextjs.org/docs/api-reference/data-fetching/get-static-props#context-parameter
......
...@@ -411,13 +411,13 @@ createNextDescribe( ...@@ -411,13 +411,13 @@ createNextDescribe(
'route-handler-edge/revalidate-360/route.js', 'route-handler-edge/revalidate-360/route.js',
'route-handler/post/route.js', 'route-handler/post/route.js',
'route-handler/revalidate-360/route.js', 'route-handler/revalidate-360/route.js',
'ssg-preview.html', 'ssg-draft-mode.html',
'ssg-preview.rsc', 'ssg-draft-mode.rsc',
'ssg-preview/[[...route]]/page.js', 'ssg-draft-mode/[[...route]]/page.js',
'ssg-preview/test-2.html', 'ssg-draft-mode/test-2.html',
'ssg-preview/test-2.rsc', 'ssg-draft-mode/test-2.rsc',
'ssg-preview/test.html', 'ssg-draft-mode/test.html',
'ssg-preview/test.rsc', 'ssg-draft-mode/test.rsc',
'ssr-auto/cache-no-store/page.js', 'ssr-auto/cache-no-store/page.js',
'ssr-auto/fetch-revalidate-zero/page.js', 'ssr-auto/fetch-revalidate-zero/page.js',
'ssr-forced/page.js', 'ssr-forced/page.js',
...@@ -603,6 +603,21 @@ createNextDescribe( ...@@ -603,6 +603,21 @@ createNextDescribe(
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]', srcRoute: '/partial-gen-params-no-additional-slug/[lang]/[slug]',
}, },
'/ssg-draft-mode': {
dataRoute: '/ssg-draft-mode.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-draft-mode/[[...route]]',
},
'/ssg-draft-mode/test': {
dataRoute: '/ssg-draft-mode/test.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-draft-mode/[[...route]]',
},
'/ssg-draft-mode/test-2': {
dataRoute: '/ssg-draft-mode/test-2.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-draft-mode/[[...route]]',
},
'/force-static/first': { '/force-static/first': {
dataRoute: '/force-static/first.rsc', dataRoute: '/force-static/first.rsc',
initialRevalidateSeconds: false, initialRevalidateSeconds: false,
...@@ -618,21 +633,6 @@ createNextDescribe( ...@@ -618,21 +633,6 @@ createNextDescribe(
initialRevalidateSeconds: 3, initialRevalidateSeconds: 3,
srcRoute: '/gen-params-dynamic-revalidate/[slug]', srcRoute: '/gen-params-dynamic-revalidate/[slug]',
}, },
'/ssg-preview': {
dataRoute: '/ssg-preview.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-preview/[[...route]]',
},
'/ssg-preview/test': {
dataRoute: '/ssg-preview/test.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-preview/[[...route]]',
},
'/ssg-preview/test-2': {
dataRoute: '/ssg-preview/test-2.rsc',
initialRevalidateSeconds: false,
srcRoute: '/ssg-preview/[[...route]]',
},
'/variable-config-revalidate/revalidate-3': { '/variable-config-revalidate/revalidate-3': {
dataRoute: '/variable-config-revalidate/revalidate-3.rsc', dataRoute: '/variable-config-revalidate/revalidate-3.rsc',
initialRevalidateSeconds: 3, initialRevalidateSeconds: 3,
...@@ -734,6 +734,12 @@ createNextDescribe( ...@@ -734,6 +734,12 @@ createNextDescribe(
'^\\/partial\\-gen\\-params\\-no\\-additional\\-slug\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$' '^\\/partial\\-gen\\-params\\-no\\-additional\\-slug\\/([^\\/]+?)\\/([^\\/]+?)(?:\\/)?$'
), ),
}, },
'/ssg-draft-mode/[[...route]]': {
dataRoute: '/ssg-draft-mode/[[...route]].rsc',
dataRouteRegex: '^\\/ssg\\-draft\\-mode(?:\\/(.+?))?\\.rsc$',
fallback: null,
routeRegex: '^\\/ssg\\-draft\\-mode(?:\\/(.+?))?(?:\\/)?$',
},
'/force-static/[slug]': { '/force-static/[slug]': {
dataRoute: '/force-static/[slug].rsc', dataRoute: '/force-static/[slug].rsc',
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -744,16 +750,6 @@ createNextDescribe( ...@@ -744,16 +750,6 @@ createNextDescribe(
'^\\/force\\-static\\/([^\\/]+?)(?:\\/)?$' '^\\/force\\-static\\/([^\\/]+?)(?:\\/)?$'
), ),
}, },
'/ssg-preview/[[...route]]': {
dataRoute: '/ssg-preview/[[...route]].rsc',
dataRouteRegex: normalizeRegEx(
'^\\/ssg\\-preview(?:\\/(.+?))?\\.rsc$'
),
fallback: null,
routeRegex: normalizeRegEx(
'^\\/ssg\\-preview(?:\\/(.+?))?(?:\\/)?$'
),
},
'/static-to-dynamic-error-forced/[id]': { '/static-to-dynamic-error-forced/[id]': {
dataRoute: '/static-to-dynamic-error-forced/[id].rsc', dataRoute: '/static-to-dynamic-error-forced/[id].rsc',
dataRouteRegex: normalizeRegEx( dataRouteRegex: normalizeRegEx(
...@@ -1324,14 +1320,14 @@ createNextDescribe( ...@@ -1324,14 +1320,14 @@ createNextDescribe(
}, 'success') }, 'success')
}) })
it('Should not throw Dynamic Server Usage error when using generateStaticParams with previewData', async () => { it('should not throw Dynamic Server Usage error when using generateStaticParams with draftMode', async () => {
const browserOnIndexPage = await next.browser('/ssg-preview') const browserOnIndexPage = await next.browser('/ssg-draft-mode')
const content = await browserOnIndexPage const content = await browserOnIndexPage
.elementByCss('#preview-data') .elementByCss('#draft-mode')
.text() .text()
expect(content).toContain('previewData') expect(content).toBe('{"result":{"enabled":false}}')
}) })
it('should force SSR correctly for headers usage', async () => { it('should force SSR correctly for headers usage', async () => {
......
import { previewData } from 'next/headers' import { draftMode } from 'next/headers'
export default function Page() { export default function Page() {
const previewDataResult = previewData() const result = draftMode()
return ( return (
<main> <main>
<pre id="preview-data"> <pre id="draft-mode">{JSON.stringify({ result })}</pre>
{JSON.stringify({ previewData: previewDataResult })}
</pre>
</main> </main>
) )
} }
......
import { draftMode } from 'next/headers'
export function GET() {
draftMode().disable()
return new Response(
'Disabled in Route Handler using draftMode().enable(), check cookies'
)
}
import { draftMode } from 'next/headers'
export function GET() {
draftMode().enable()
return new Response(
'Enabled in Route Handler using draftMode().enable(), check cookies'
)
}
import React from 'react'
export default function Layout({ children }) {
return (
<html>
<head>
<title>Draft Mode</title>
</head>
<body>{children}</body>
</html>
)
}
import React from 'react'
import { draftMode } from 'next/headers'
export default function Page() {
const { enabled } = draftMode()
return (
<>
<h1>Draft Mode Test</h1>
<p>
Random: <em id="rand">{Math.random()}</em>
</p>
<p>
State: <strong id="mode">{enabled ? 'ENABLED' : 'DISABLED'}</strong>
</p>
</>
)
}
import { draftMode } from 'next/headers'
export function GET() {
const { enabled } = draftMode()
return new Response(enabled ? 'ENABLED' : 'DISABLED')
}
import React from 'react'
import { draftMode } from 'next/headers'
export const runtime = 'experimental-edge'
export default function Page() {
const { enabled } = draftMode()
return (
<>
<h1>Draft Mode in Edge</h1>
<p>
Random: <em id="rand">{Math.random()}</em>
</p>
<p>
State: <strong id="mode">{enabled ? 'ENABLED' : 'DISABLED'}</strong>
</p>
</>
)
}
import { draftMode } from 'next/headers'
export const runtime = 'edge'
export function GET() {
const { enabled } = draftMode()
return new Response(enabled ? 'ENABLED' : 'DISABLED')
}
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'app dir - draft mode',
{
files: __dirname,
},
({ next }) => {
let Cookie = ''
it('should be disabled', async () => {
const $ = await next.render$('/')
expect($('#mode').text()).toBe('DISABLED')
})
it('should be disabled from api route handler', async () => {
const res = await next.fetch('/state')
expect(await res.text()).toBe('DISABLED')
})
it('should have set-cookie header on enable', async () => {
const res = await next.fetch('/enable')
const h = res.headers.get('set-cookie') || ''
Cookie = h.split(';').find((c) => c.startsWith('__prerender_bypass'))
expect(Cookie).toBeDefined()
})
it('should be enabled from page when draft mode enabled', async () => {
const opts = { headers: { Cookie } }
const $ = await next.render$('/', {}, opts)
expect($('#mode').text()).toBe('ENABLED')
})
it('should be enabled from api route handler when draft mode enabled', async () => {
const opts = { headers: { Cookie } }
const res = await next.fetch('/state', opts)
expect(await res.text()).toBe('ENABLED')
})
}
)
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'app dir - draft mode',
{
files: __dirname,
},
({ next, isNextDev }) => {
let initialRand = 'unintialized'
let Cookie = ''
it('should use initial rand when draft mode is disabled', async () => {
const $ = await next.render$('/')
expect($('#mode').text()).toBe('DISABLED')
expect($('#rand').text()).toBeDefined()
initialRand = $('#rand').text()
})
if (!isNextDev) {
it('should not generate rand when draft mode disabled during next start', async () => {
const $ = await next.render$('/')
expect($('#mode').text()).toBe('DISABLED')
expect($('#rand').text()).toBe(initialRand)
})
}
it('should be disabled from api route handler', async () => {
const res = await next.fetch('/state')
expect(await res.text()).toBe('DISABLED')
})
it('should have set-cookie header on enable', async () => {
const res = await next.fetch('/enable')
const h = res.headers.get('set-cookie') || ''
Cookie = h.split(';').find((c) => c.startsWith('__prerender_bypass'))
expect(Cookie).toBeDefined()
})
it('should genenerate rand when draft mode enabled', async () => {
const opts = { headers: { Cookie } }
const $ = await next.render$('/', {}, opts)
expect($('#mode').text()).toBe('ENABLED')
expect($('#rand').text()).not.toBe(initialRand)
})
it('should be enabled from api route handler when draft mode enabled', async () => {
const opts = { headers: { Cookie } }
const res = await next.fetch('/state', opts)
expect(await res.text()).toBe('ENABLED')
})
}
)
module.exports = {
experimental: {
appDir: true,
},
}
import { draftMode } from 'next/headers'
export function GET() {
draftMode().enable()
return new Response(
'Enabled in Route Handler with draftMode().enable(), check cookies'
)
}
import { draftMode } from 'next/headers'
export default function Page() {
const { enabled } = draftMode()
return (
<>
<h1>hello from /hooks/use-draft-mode</h1>
<p>
Rand: <em id="rand">{Math.random()}</em>
</p>
<h2 id="draft-mode-val">{enabled ? 'ENABLED' : 'DISABLED'}</h2>
</>
)
}
import { previewData } from 'next/headers'
export default function Page() {
const data = previewData()
const hasData = !!data && data.key === 'value'
return (
<>
<h1>hello from /hooks/use-preview-data</h1>
{hasData ? (
<h2 id="has-preview-data">Has preview data</h2>
) : (
<h2 id="does-not-have-preview-data">Does not have preview data</h2>
)}
</>
)
}
...@@ -76,6 +76,35 @@ createNextDescribe( ...@@ -76,6 +76,35 @@ createNextDescribe(
} }
}) })
describe('useDraftMode', () => {
let initialRand = 'unintialized'
it('should use initial rand when draft mode be disabled', async () => {
const $ = await next.render$('/hooks/use-draft-mode')
expect($('#draft-mode-val').text()).toBe('DISABLED')
expect($('#rand').text()).toBeDefined()
initialRand = $('#rand').text()
})
it('should genenerate rand when draft mode enabled', async () => {
const res = await next.fetch('/enable')
const h = res.headers.get('set-cookie') || ''
const cookie = h
.split(';')
.find((c) => c.startsWith('__prerender_bypass'))
const $ = await next.render$(
'/hooks/use-draft-mode',
{},
{
headers: {
Cookie: cookie,
},
}
)
expect($('#draft-mode-val').text()).toBe('ENABLED')
expect($('#rand').text()).not.toBe(initialRand)
})
})
describe('useRouter', () => { describe('useRouter', () => {
it('should allow access to the router', async () => { it('should allow access to the router', async () => {
const browser = await next.browser('/hooks/use-router') const browser = await next.browser('/hooks/use-router')
......
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