Unverified Commit 3229ed79 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Support `force-static` on App Routes (#46693)

Supports `export const dynamic = 'force-static'` on App Routes. This strips pieces of information from the request object to ensure subsequent requests don't accidentally cache user specific data:

- Removes `searchParams`
- Removes `headers`
- Removes `cookies`
- Removes `host`
- Removes `port`
- Removes `protocol`

[NEXT-682](https://linear.app/vercel/issue/NEXT-682/force-static-doesnt-work-with-app-routes)
parent e7ee310f
...@@ -16,6 +16,6 @@ export interface AsyncStorageWrapper<Store extends {}, Context extends {}> { ...@@ -16,6 +16,6 @@ export interface AsyncStorageWrapper<Store extends {}, Context extends {}> {
wrap<Result>( wrap<Result>(
storage: AsyncLocalStorage<Store>, storage: AsyncLocalStorage<Store>,
context: Context, context: Context,
callback: () => Result callback: (store: Store) => Result
): Result ): Result
} }
...@@ -49,7 +49,7 @@ export class RequestAsyncStorageWrapper ...@@ -49,7 +49,7 @@ export class RequestAsyncStorageWrapper
public wrap<Result>( public wrap<Result>(
storage: AsyncLocalStorage<RequestStore>, storage: AsyncLocalStorage<RequestStore>,
context: RequestContext, context: RequestContext,
callback: () => Result callback: (store: RequestStore) => Result
): Result { ): Result {
return RequestAsyncStorageWrapper.wrap(storage, context, callback) return RequestAsyncStorageWrapper.wrap(storage, context, callback)
} }
...@@ -60,7 +60,7 @@ export class RequestAsyncStorageWrapper ...@@ -60,7 +60,7 @@ export class RequestAsyncStorageWrapper
public static wrap<Result>( public static wrap<Result>(
storage: AsyncLocalStorage<RequestStore>, storage: AsyncLocalStorage<RequestStore>,
{ req, res, renderOpts }: RequestContext, { req, res, renderOpts }: RequestContext,
callback: () => Result callback: (store: RequestStore) => Result
): Result { ): Result {
// Reads of this are cached on the `req` object, so this should resolve // 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 // instantly. There's no need to pass this data down from a previous
...@@ -105,6 +105,6 @@ export class RequestAsyncStorageWrapper ...@@ -105,6 +105,6 @@ export class RequestAsyncStorageWrapper
previewData, previewData,
} }
return storage.run(store, callback) return storage.run(store, callback, store)
} }
} }
...@@ -20,7 +20,7 @@ export class StaticGenerationAsyncStorageWrapper ...@@ -20,7 +20,7 @@ export class StaticGenerationAsyncStorageWrapper
public wrap<Result>( public wrap<Result>(
storage: AsyncLocalStorage<StaticGenerationStore>, storage: AsyncLocalStorage<StaticGenerationStore>,
context: RequestContext, context: RequestContext,
callback: () => Result callback: (store: StaticGenerationStore) => Result
): Result { ): Result {
return StaticGenerationAsyncStorageWrapper.wrap(storage, context, callback) return StaticGenerationAsyncStorageWrapper.wrap(storage, context, callback)
} }
...@@ -31,7 +31,7 @@ export class StaticGenerationAsyncStorageWrapper ...@@ -31,7 +31,7 @@ export class StaticGenerationAsyncStorageWrapper
public static wrap<Result>( public static wrap<Result>(
storage: AsyncLocalStorage<StaticGenerationStore>, storage: AsyncLocalStorage<StaticGenerationStore>,
{ pathname, renderOpts }: RequestContext, { pathname, renderOpts }: RequestContext,
callback: () => Result callback: (store: StaticGenerationStore) => Result
): Result { ): Result {
/** /**
* Rules of Static & Dynamic HTML: * Rules of Static & Dynamic HTML:
...@@ -58,6 +58,6 @@ export class StaticGenerationAsyncStorageWrapper ...@@ -58,6 +58,6 @@ export class StaticGenerationAsyncStorageWrapper
} }
;(renderOpts as any).store = store ;(renderOpts as any).store = store
return storage.run(store, callback) return storage.run(store, callback, store)
} }
} }
...@@ -31,13 +31,12 @@ import type { ModuleLoader } from '../helpers/module-loader/module-loader' ...@@ -31,13 +31,12 @@ import type { ModuleLoader } from '../helpers/module-loader/module-loader'
import { RouteHandler } from './route-handler' import { RouteHandler } from './route-handler'
import * as Log from '../../../build/output/log' import * as Log from '../../../build/output/log'
import { patchFetch } from '../../lib/patch-fetch' import { patchFetch } from '../../lib/patch-fetch'
import { import { StaticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage'
StaticGenerationAsyncStorage,
StaticGenerationStore,
} from '../../../client/components/static-generation-async-storage'
import { StaticGenerationAsyncStorageWrapper } from '../../async-storage/static-generation-async-storage-wrapper' import { StaticGenerationAsyncStorageWrapper } from '../../async-storage/static-generation-async-storage-wrapper'
import { IncrementalCache } from '../../lib/incremental-cache' import { IncrementalCache } from '../../lib/incremental-cache'
import { AppConfig } from '../../../build/utils' import { AppConfig } from '../../../build/utils'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies'
import { NextURL } from '../../web/next-url'
// TODO-APP: This module has a dynamic require so when bundling for edge it causes issues. // TODO-APP: This module has a dynamic require so when bundling for edge it causes issues.
const NodeModuleLoader = const NodeModuleLoader =
...@@ -195,6 +194,143 @@ export async function sendResponse( ...@@ -195,6 +194,143 @@ export async function sendResponse(
} }
} }
function cleanURL(urlString: string): string {
const url = new URL(urlString)
url.host = 'localhost:3000'
url.search = ''
url.protocol = 'http'
return url.toString()
}
function proxyRequest(req: NextRequest, module: AppRouteModule): NextRequest {
function handleNextUrlBailout(prop: string | symbol) {
switch (prop) {
case 'search':
case 'searchParams':
case 'toString':
case 'href':
case 'origin':
module.staticGenerationBailout(`nextUrl.${prop as string}`)
return
default:
return
}
}
const cache: {
url?: string
toString?: () => string
headers?: Headers
cookies?: RequestCookies
searchParams?: URLSearchParams
} = {}
const handleForceStatic = (url: string, prop: string) => {
switch (prop) {
case 'search':
return ''
case 'searchParams':
if (!cache.searchParams) cache.searchParams = new URLSearchParams()
return cache.searchParams
case 'url':
case 'href':
if (!cache.url) cache.url = cleanURL(url)
return cache.url
case 'toJSON':
case 'toString':
if (!cache.url) cache.url = cleanURL(url)
if (!cache.toString) cache.toString = () => cache.url!
return cache.toString
case 'headers':
if (!cache.headers) cache.headers = new Headers()
return cache.headers
case 'cookies':
if (!cache.headers) cache.headers = new Headers()
if (!cache.cookies) cache.cookies = new RequestCookies(cache.headers)
return cache.cookies
case 'clone':
if (!cache.url) cache.url = cleanURL(url)
return () => new NextURL(cache.url!)
default:
break
}
}
const wrappedNextUrl = new Proxy(req.nextUrl, {
get(target, prop) {
handleNextUrlBailout(prop)
if (
module.handlers.dynamic === 'force-static' &&
typeof prop === 'string'
) {
const result = handleForceStatic(target.href, prop)
if (result !== undefined) return result
}
return (target as any)[prop]
},
set(target, prop, value) {
handleNextUrlBailout(prop)
;(target as any)[prop] = value
return true
},
})
const handleReqBailout = (prop: string | symbol) => {
switch (prop) {
case 'headers':
module.headerHooks.headers()
return
// if request.url is accessed directly instead of
// request.nextUrl we bail since it includes query
// values that can be relied on dynamically
case 'url':
case 'body':
case 'blob':
case 'json':
case 'text':
case 'arrayBuffer':
case 'formData':
module.staticGenerationBailout(`request.${prop}`)
return
default:
return
}
}
return new Proxy(req, {
get(target, prop) {
handleReqBailout(prop)
if (prop === 'nextUrl') {
return wrappedNextUrl
}
if (
module.handlers.dynamic === 'force-static' &&
typeof prop === 'string'
) {
const result = handleForceStatic(target.url, prop)
if (result !== undefined) return result
}
return (target as any)[prop]
},
set(target, prop, value) {
handleReqBailout(prop)
;(target as any)[prop] = value
return true
},
})
}
export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
constructor( constructor(
private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper< private readonly requestAsyncLocalStorageWrapper: AsyncStorageWrapper<
...@@ -314,9 +450,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -314,9 +450,7 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
supportsDynamicHTML: false, supportsDynamicHTML: false,
}, },
}, },
() => { (staticGenerationStore) => {
const _req = (request ? request : wrapRequest(req)) as NextRequest
// We can currently only statically optimize if only GET/HEAD // We can currently only statically optimize if only GET/HEAD
// are used as a Prerender can't be used conditionally based // are used as a Prerender can't be used conditionally based
// on the method currently // on the method currently
...@@ -337,90 +471,33 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> { ...@@ -337,90 +471,33 @@ export class AppRouteRouteHandler implements RouteHandler<AppRouteRouteMatch> {
) )
} }
const staticGenerationStore = switch (module.handlers.dynamic) {
staticGenerationAsyncStorage.getStore() || case 'force-dynamic':
({} as StaticGenerationStore) staticGenerationStore.forceDynamic = true
module.staticGenerationBailout(`dynamic = 'force-dynamic'`)
const dynamicConfig = module.handlers.dynamic break
const revalidateConfig = module.handlers.revalidate case 'force-static':
let defaultRevalidate: number | false = false staticGenerationStore.forceStatic = true
break
if (dynamicConfig === 'force-dynamic') { default:
module.staticGenerationBailout(`dynamic = 'force-dynamic'`) // TODO: implement
} break
if (typeof revalidateConfig !== 'undefined') {
defaultRevalidate = revalidateConfig
if (typeof staticGenerationStore.revalidate === 'undefined') {
staticGenerationStore.revalidate = defaultRevalidate
}
} }
const handleNextUrlBailout = (prop: string | symbol) => { if (typeof staticGenerationStore.revalidate === 'undefined') {
if ( staticGenerationStore.revalidate =
[ module.handlers.revalidate ?? false
'search',
'searchParams',
'toString',
'href',
'origin',
].includes(prop as string)
) {
module.staticGenerationBailout(`nextUrl.${prop as string}`)
}
} }
const wrappedNextUrl = new Proxy(_req.nextUrl, { // Wrap the request so we can add additional functionality to cases
get(target, prop) { // that might change it's output or affect the rendering.
handleNextUrlBailout(prop) const wrappedRequest = proxyRequest(
return (target as any)[prop] // TODO: investigate why/how this cast is necessary/possible
}, (request ? request : wrapRequest(req)) as NextRequest,
set(target, prop, value) { module
handleNextUrlBailout(prop) )
;(target as any)[prop] = value
return true
},
})
const handleReqBailout = (prop: string | symbol) => {
if (prop === 'headers') {
return module.headerHooks.headers()
}
// if request.url is accessed directly instead of
// request.nextUrl we bail since it includes query
// values that can be relied on dynamically
if (prop === 'url') {
module.staticGenerationBailout(`request.${prop as string}`)
}
if (
[
'body',
'blob',
'json',
'text',
'arrayBuffer',
'formData',
].includes(prop as string)
) {
module.staticGenerationBailout(`request.${prop as string}`)
}
}
const wrappedReq = new Proxy(_req, { return handle(wrappedRequest, { params })
get(target, prop) {
handleReqBailout(prop)
if (prop === 'nextUrl') {
return wrappedNextUrl
}
return (target as any)[prop]
},
set(target, prop, value) {
handleReqBailout(prop)
;(target as any)[prop] = value
return true
},
})
return handle(wrappedReq, { params })
} }
) )
) )
......
...@@ -407,6 +407,35 @@ createNextDescribe( ...@@ -407,6 +407,35 @@ createNextDescribe(
}) })
}) })
describe('dynamic = "force-static"', () => {
it('strips search, headers, and domain from request', async () => {
const res = await next.fetch('/dynamic?query=true', {
headers: {
accept: 'application/json',
cookie: 'session=true',
},
})
const url = 'http://localhost:3000/dynamic'
expect(res.status).toEqual(200)
expect(await res.json()).toEqual({
nextUrl: {
href: url,
search: '',
searchParams: null,
clone: url,
},
req: {
url,
headers: null,
},
headers: null,
cookies: null,
})
})
})
if (isNextDev) { if (isNextDev) {
describe('lowercase exports', () => { describe('lowercase exports', () => {
it.each([ it.each([
......
import { cookies, headers } from 'next/headers'
import { NextResponse } from 'next/server'
export const dynamic = 'force-static'
export function GET(req: Request) {
return NextResponse.json({
nextUrl: {
href: (req as any).nextUrl.href,
search: (req as any).nextUrl.search,
searchParams: (req as any).nextUrl.searchParams.get('query'),
clone: (req as any).nextUrl.clone().toString(),
},
req: {
url: req.url,
headers: req.headers.get('accept'),
},
headers: headers().get('accept'),
cookies: cookies().get('session')?.value ?? null,
})
}
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