Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
e819e00d
Unverified
Commit
e819e00d
authored
Dec 16, 2020
by
JJ Kasper
Committed by
GitHub
Dec 16, 2020
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add required server files manifest (#20035)
This keeps track of required server files in a manifest file
parent
5d5383b2
Hide whitespace changes
Inline
Side-by-side
Showing
10 changed files
with
705 additions
and
157 deletions
+705
-157
index.ts
packages/next/build/index.ts
+64
-5
page-handler.ts
...ld/webpack/loaders/next-serverless-loader/page-handler.ts
+9
-100
utils.ts
...ext/build/webpack/loaders/next-serverless-loader/utils.ts
+137
-13
font-stylesheet-gathering-plugin.ts
...build/webpack/plugins/font-stylesheet-gathering-plugin.ts
+6
-3
constants.ts
packages/next/next-server/lib/constants.ts
+1
-0
next-server.ts
packages/next/next-server/server/next-server.ts
+121
-36
[slug].js
...integration/required-server-files/pages/dynamic/[slug].js
+23
-0
[slug].js
...ntegration/required-server-files/pages/fallback/[slug].js
+30
-0
index.js
test/integration/required-server-files/pages/index.js
+21
-0
index.test.js
test/integration/required-server-files/test/index.test.js
+293
-0
No files found.
packages/next/build/index.ts
View file @
e819e00d
...
@@ -25,17 +25,21 @@ import { loadEnvConfig } from '@next/env'
...
@@ -25,17 +25,21 @@ import { loadEnvConfig } from '@next/env'
import
{
recursiveDelete
}
from
'../lib/recursive-delete'
import
{
recursiveDelete
}
from
'../lib/recursive-delete'
import
{
verifyTypeScriptSetup
}
from
'../lib/verifyTypeScriptSetup'
import
{
verifyTypeScriptSetup
}
from
'../lib/verifyTypeScriptSetup'
import
{
import
{
BUILD_ID_FILE
,
BUILD_MANIFEST
,
BUILD_MANIFEST
,
CLIENT_STATIC_FILES_PATH
,
CLIENT_STATIC_FILES_PATH
,
EXPORT_DETAIL
,
EXPORT_DETAIL
,
EXPORT_MARKER
,
EXPORT_MARKER
,
FONT_MANIFEST
,
IMAGES_MANIFEST
,
IMAGES_MANIFEST
,
PAGES_MANIFEST
,
PAGES_MANIFEST
,
PHASE_PRODUCTION_BUILD
,
PHASE_PRODUCTION_BUILD
,
PRERENDER_MANIFEST
,
PRERENDER_MANIFEST
,
REACT_LOADABLE_MANIFEST
,
ROUTES_MANIFEST
,
ROUTES_MANIFEST
,
SERVERLESS_DIRECTORY
,
SERVERLESS_DIRECTORY
,
SERVER_DIRECTORY
,
SERVER_DIRECTORY
,
SERVER_FILES_MANIFEST
,
}
from
'../next-server/lib/constants'
}
from
'../next-server/lib/constants'
import
{
import
{
getRouteRegex
,
getRouteRegex
,
...
@@ -343,6 +347,39 @@ export default async function build(
...
@@ -343,6 +347,39 @@ export default async function build(
'utf8'
'utf8'
)
)
const
manifestPath
=
path
.
join
(
distDir
,
isLikeServerless
?
SERVERLESS_DIRECTORY
:
SERVER_DIRECTORY
,
PAGES_MANIFEST
)
const
requiredServerFiles
=
{
version
:
1
,
config
:
{
...
config
,
compress
:
false
,
configFile
:
undefined
,
},
files
:
[
ROUTES_MANIFEST
,
path
.
relative
(
distDir
,
manifestPath
),
BUILD_MANIFEST
,
PRERENDER_MANIFEST
,
REACT_LOADABLE_MANIFEST
,
path
.
join
(
isLikeServerless
?
SERVERLESS_DIRECTORY
:
SERVER_DIRECTORY
,
FONT_MANIFEST
),
BUILD_ID_FILE
,
].
map
((
file
)
=>
path
.
join
(
config
.
distDir
,
file
)),
ignore
:
[
path
.
relative
(
dir
,
path
.
join
(
path
.
dirname
(
require
.
resolve
(
'sharp'
)),
'**/*'
)
),
],
}
const
configs
=
await
Promise
.
all
([
const
configs
=
await
Promise
.
all
([
getBaseWebpackConfig
(
dir
,
{
getBaseWebpackConfig
(
dir
,
{
tracer
,
tracer
,
...
@@ -465,11 +502,6 @@ export default async function build(
...
@@ -465,11 +502,6 @@ export default async function build(
prefixText
:
`
${
Log
.
prefixes
.
info
}
Collecting page data`
,
prefixText
:
`
${
Log
.
prefixes
.
info
}
Collecting page data`
,
})
})
const
manifestPath
=
path
.
join
(
distDir
,
isLikeServerless
?
SERVERLESS_DIRECTORY
:
SERVER_DIRECTORY
,
PAGES_MANIFEST
)
const
buildManifestPath
=
path
.
join
(
distDir
,
BUILD_MANIFEST
)
const
buildManifestPath
=
path
.
join
(
distDir
,
BUILD_MANIFEST
)
const
ssgPages
=
new
Set
<
string
>
()
const
ssgPages
=
new
Set
<
string
>
()
...
@@ -515,6 +547,8 @@ export default async function build(
...
@@ -515,6 +547,8 @@ export default async function build(
false
false
))
))
let
hasSsrAmpPages
=
false
const
analysisBegin
=
process
.
hrtime
()
const
analysisBegin
=
process
.
hrtime
()
await
Promise
.
all
(
await
Promise
.
all
(
pageKeys
.
map
(
async
(
page
)
=>
{
pageKeys
.
map
(
async
(
page
)
=>
{
...
@@ -575,6 +609,13 @@ export default async function build(
...
@@ -575,6 +609,13 @@ export default async function build(
config
.
i18n
?.
defaultLocale
config
.
i18n
?.
defaultLocale
)
)
if
(
workerResult
.
isStatic
===
false
&&
(
workerResult
.
isHybridAmp
||
workerResult
.
isAmpOnly
)
)
{
hasSsrAmpPages
=
true
}
if
(
workerResult
.
isHybridAmp
)
{
if
(
workerResult
.
isHybridAmp
)
{
isHybridAmp
=
true
isHybridAmp
=
true
hybridAmpPages
.
add
(
page
)
hybridAmpPages
.
add
(
page
)
...
@@ -637,6 +678,18 @@ export default async function build(
...
@@ -637,6 +678,18 @@ export default async function build(
)
)
staticCheckWorkers
.
end
()
staticCheckWorkers
.
end
()
if
(
!
hasSsrAmpPages
)
{
requiredServerFiles
.
ignore
.
push
(
path
.
relative
(
dir
,
path
.
join
(
path
.
dirname
(
require
.
resolve
(
'@ampproject/toolbox-optimizer'
)),
'**/*'
)
)
)
}
if
(
serverPropsPages
.
size
>
0
||
ssgPages
.
size
>
0
)
{
if
(
serverPropsPages
.
size
>
0
||
ssgPages
.
size
>
0
)
{
// We update the routes manifest after the build with the
// We update the routes manifest after the build with the
// data routes since we can't determine these until after build
// data routes since we can't determine these until after build
...
@@ -712,6 +765,12 @@ export default async function build(
...
@@ -712,6 +765,12 @@ export default async function build(
await
writeBuildId
(
distDir
,
buildId
)
await
writeBuildId
(
distDir
,
buildId
)
await
promises
.
writeFile
(
path
.
join
(
distDir
,
SERVER_FILES_MANIFEST
),
JSON
.
stringify
(
requiredServerFiles
),
'utf8'
)
const
finalPrerenderRoutes
:
{
[
route
:
string
]:
SsgRoute
}
=
{}
const
finalPrerenderRoutes
:
{
[
route
:
string
]:
SsgRoute
}
=
{}
const
tbdPrerenderRoutes
:
string
[]
=
[]
const
tbdPrerenderRoutes
:
string
[]
=
[]
let
ssgNotFoundPaths
:
string
[]
=
[]
let
ssgNotFoundPaths
:
string
[]
=
[]
...
...
packages/next/build/webpack/loaders/next-serverless-loader/page-handler.ts
View file @
e819e00d
import
{
parse
as
parseQs
}
from
'querystring'
import
{
IncomingMessage
,
ServerResponse
}
from
'http'
import
{
IncomingMessage
,
ServerResponse
}
from
'http'
import
{
parse
as
parseUrl
,
format
as
formatUrl
,
UrlWithParsedQuery
}
from
'url'
import
{
parse
as
parseUrl
,
format
as
formatUrl
,
UrlWithParsedQuery
}
from
'url'
import
{
isResSent
}
from
'../../../../next-server/lib/utils'
import
{
isResSent
}
from
'../../../../next-server/lib/utils'
...
@@ -14,7 +13,6 @@ import {
...
@@ -14,7 +13,6 @@ import {
}
from
'../../../../next-server/server/api-utils'
}
from
'../../../../next-server/server/api-utils'
import
{
getRedirectStatus
}
from
'../../../../lib/load-custom-routes'
import
{
getRedirectStatus
}
from
'../../../../lib/load-custom-routes'
import
getRouteNoAssetPath
from
'../../../../next-server/lib/router/utils/get-route-from-asset-path'
import
getRouteNoAssetPath
from
'../../../../next-server/lib/router/utils/get-route-from-asset-path'
import
{
getRouteMatcher
}
from
'../../../../next-server/lib/router/utils/route-matcher'
import
{
PERMANENT_REDIRECT_STATUS
}
from
'../../../../next-server/lib/constants'
import
{
PERMANENT_REDIRECT_STATUS
}
from
'../../../../next-server/lib/constants'
export
function
getPageHandler
(
ctx
:
ServerlessHandlerCtx
)
{
export
function
getPageHandler
(
ctx
:
ServerlessHandlerCtx
)
{
...
@@ -56,7 +54,10 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
...
@@ -56,7 +54,10 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
handleBasePath
,
handleBasePath
,
defaultRouteRegex
,
defaultRouteRegex
,
dynamicRouteMatcher
,
dynamicRouteMatcher
,
interpolateDynamicPath
,
getParamsFromRouteMatches
,
normalizeDynamicRouteParams
,
normalizeDynamicRouteParams
,
normalizeVercelUrl
,
}
=
getUtils
(
ctx
)
}
=
getUtils
(
ctx
)
async
function
renderReqToHTML
(
async
function
renderReqToHTML
(
...
@@ -222,116 +223,24 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
...
@@ -222,116 +223,24 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
!
hasValidParams
&&
!
hasValidParams
&&
req
.
headers
?.[
'x-now-route-matches'
]
req
.
headers
?.[
'x-now-route-matches'
]
)
{
)
{
nowParams
=
getRouteMatcher
(
nowParams
=
getParamsFromRouteMatches
(
req
,
renderOpts
,
detectedLocale
)
(
function
()
{
const
{
groups
,
routeKeys
}
=
defaultRouteRegex
!
return
{
re
:
{
// Simulate a RegExp match from the \`req.url\` input
exec
:
(
str
:
string
)
=>
{
const
obj
=
parseQs
(
str
)
// favor named matches if available
const
routeKeyNames
=
Object
.
keys
(
routeKeys
||
{})
const
filterLocaleItem
=
(
val
:
string
|
string
[])
=>
{
if
(
i18n
)
{
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const
isCatchAll
=
Array
.
isArray
(
val
)
const
_val
=
isCatchAll
?
val
[
0
]
:
val
if
(
typeof
_val
===
'string'
&&
i18n
.
locales
.
some
((
item
)
=>
{
if
(
item
.
toLowerCase
()
===
_val
.
toLowerCase
())
{
detectedLocale
=
item
renderOpts
.
locale
=
detectedLocale
return
true
}
return
false
})
)
{
// remove the locale item from the match
if
(
isCatchAll
)
{
;(
val
as
string
[]).
splice
(
0
,
1
)
}
// the value is only a locale item and
// shouldn't be added
return
isCatchAll
?
val
.
length
===
0
:
true
}
}
return
false
}
if
(
routeKeyNames
.
every
((
name
)
=>
obj
[
name
]))
{
return
routeKeyNames
.
reduce
((
prev
,
keyName
)
=>
{
const
paramName
=
routeKeys
?.[
keyName
]
if
(
paramName
&&
!
filterLocaleItem
(
obj
[
keyName
]))
{
prev
[
groups
[
paramName
].
pos
]
=
obj
[
keyName
]
}
return
prev
},
{}
as
any
)
}
return
Object
.
keys
(
obj
).
reduce
((
prev
,
key
)
=>
{
if
(
!
filterLocaleItem
(
obj
[
key
]))
{
return
Object
.
assign
(
prev
,
{
[
key
]:
obj
[
key
],
})
}
return
prev
},
{})
},
},
groups
,
}
})()
as
any
)(
req
.
headers
[
'x-now-route-matches'
]
as
string
)
}
}
// make sure to set renderOpts to the correct params e.g. _params
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
// if provided from worker or params if we're parsing them here
renderOpts
.
params
=
_params
||
params
renderOpts
.
params
=
_params
||
params
// make sure to normalize req.url on Vercel to strip dynamic params
normalizeVercelUrl
(
req
,
!!
trustQuery
)
// from the query which are added during routing
if
(
pageIsDynamic
&&
trustQuery
&&
defaultRouteRegex
)
{
const
_parsedUrl
=
parseUrl
(
req
.
url
!
,
true
)
delete
(
_parsedUrl
as
any
).
search
for
(
const
param
of
Object
.
keys
(
defaultRouteRegex
.
groups
))
{
delete
_parsedUrl
.
query
[
param
]
}
req
.
url
=
formatUrl
(
_parsedUrl
)
}
// normalize request URL/asPath for fallback/revalidate pages since the
// normalize request URL/asPath for fallback/revalidate pages since the
// proxy sets the request URL to the output's path for fallback pages
// proxy sets the request URL to the output's path for fallback pages
if
(
pageIsDynamic
&&
nowParams
&&
defaultRouteRegex
)
{
if
(
pageIsDynamic
&&
nowParams
&&
defaultRouteRegex
)
{
const
_parsedUrl
=
parseUrl
(
req
.
url
!
)
const
_parsedUrl
=
parseUrl
(
req
.
url
!
)
for
(
const
param
of
Object
.
keys
(
defaultRouteRegex
.
groups
))
{
_parsedUrl
.
pathname
=
interpolateDynamicPath
(
const
{
optional
,
repeat
}
=
defaultRouteRegex
.
groups
[
param
]
_parsedUrl
.
pathname
!
,
let
builtParam
=
`[
${
repeat
?
'...'
:
''
}${
param
}
]`
nowParams
)
if
(
optional
)
{
builtParam
=
`[
${
builtParam
}
]`
}
const
paramIdx
=
_parsedUrl
.
pathname
!
.
indexOf
(
builtParam
)
if
(
paramIdx
>
-
1
)
{
_parsedUrl
.
pathname
=
_parsedUrl
.
pathname
!
.
substr
(
0
,
paramIdx
)
+
encodeURI
((
nowParams
as
any
)[
param
]
||
''
)
+
_parsedUrl
.
pathname
!
.
substr
(
paramIdx
+
builtParam
.
length
)
}
}
parsedUrl
.
pathname
=
_parsedUrl
.
pathname
parsedUrl
.
pathname
=
_parsedUrl
.
pathname
req
.
url
=
formatUrl
(
_parsedUrl
)
req
.
url
=
formatUrl
(
_parsedUrl
)
}
}
...
...
packages/next/build/webpack/loaders/next-serverless-loader/utils.ts
View file @
e819e00d
import
{
IncomingMessage
,
ServerResponse
}
from
'http'
import
{
IncomingMessage
,
ServerResponse
}
from
'http'
import
{
format
as
formatUrl
,
UrlWithParsedQuery
}
from
'url'
import
{
format
as
formatUrl
,
UrlWithParsedQuery
,
parse
as
parseUrl
}
from
'url'
import
{
ParsedUrlQuery
}
from
'querystring'
import
{
parse
as
parseQs
,
ParsedUrlQuery
}
from
'querystring'
import
{
Rewrite
}
from
'../../../../lib/load-custom-routes'
import
{
Rewrite
}
from
'../../../../lib/load-custom-routes'
import
{
normalizeLocalePath
}
from
'../../../../next-server/lib/i18n/normalize-locale-path'
import
{
normalizeLocalePath
}
from
'../../../../next-server/lib/i18n/normalize-locale-path'
import
pathMatch
from
'../../../../next-server/lib/router/utils/path-match'
import
pathMatch
from
'../../../../next-server/lib/router/utils/path-match'
...
@@ -20,6 +20,7 @@ import { detectDomainLocale } from '../../../../next-server/lib/i18n/detect-doma
...
@@ -20,6 +20,7 @@ import { detectDomainLocale } from '../../../../next-server/lib/i18n/detect-doma
import
{
denormalizePagePath
}
from
'../../../../next-server/server/denormalize-page-path'
import
{
denormalizePagePath
}
from
'../../../../next-server/server/denormalize-page-path'
import
cookie
from
'next/dist/compiled/cookie'
import
cookie
from
'next/dist/compiled/cookie'
import
{
TEMPORARY_REDIRECT_STATUS
}
from
'../../../../next-server/lib/constants'
import
{
TEMPORARY_REDIRECT_STATUS
}
from
'../../../../next-server/lib/constants'
import
{
NextConfig
}
from
'../../../../next-server/server/config'
const
getCustomRouteMatcher
=
pathMatch
(
true
)
const
getCustomRouteMatcher
=
pathMatch
(
true
)
...
@@ -54,16 +55,7 @@ export type ServerlessHandlerCtx = {
...
@@ -54,16 +55,7 @@ export type ServerlessHandlerCtx = {
poweredByHeader
:
boolean
poweredByHeader
:
boolean
canonicalBase
:
string
canonicalBase
:
string
encodedPreviewProps
:
__ApiPreviewProps
encodedPreviewProps
:
__ApiPreviewProps
i18n
?:
{
i18n
?:
NextConfig
[
'i18n'
]
localeDetection
?:
false
locales
:
string
[]
defaultLocale
:
string
domains
:
Array
<
{
domain
:
string
locales
:
string
[]
defaultLocale
:
string
}
>
}
experimental
:
{
experimental
:
{
initServer
:
()
=>
Promise
<
any
>
initServer
:
()
=>
Promise
<
any
>
onError
:
({
err
}:
{
err
:
Error
})
=>
Promise
<
any
>
onError
:
({
err
}:
{
err
:
Error
})
=>
Promise
<
any
>
...
@@ -76,7 +68,13 @@ export function getUtils({
...
@@ -76,7 +68,13 @@ export function getUtils({
basePath
,
basePath
,
rewrites
,
rewrites
,
pageIsDynamic
,
pageIsDynamic
,
}:
ServerlessHandlerCtx
)
{
}:
{
page
:
ServerlessHandlerCtx
[
'page'
]
i18n
?:
ServerlessHandlerCtx
[
'i18n'
]
basePath
:
ServerlessHandlerCtx
[
'basePath'
]
rewrites
:
ServerlessHandlerCtx
[
'rewrites'
]
pageIsDynamic
:
ServerlessHandlerCtx
[
'pageIsDynamic'
]
})
{
let
defaultRouteRegex
:
ReturnType
<
typeof
getRouteRegex
>
|
undefined
let
defaultRouteRegex
:
ReturnType
<
typeof
getRouteRegex
>
|
undefined
let
dynamicRouteMatcher
:
ReturnType
<
typeof
getRouteMatcher
>
|
undefined
let
dynamicRouteMatcher
:
ReturnType
<
typeof
getRouteMatcher
>
|
undefined
let
defaultRouteMatches
:
ParsedUrlQuery
|
undefined
let
defaultRouteMatches
:
ParsedUrlQuery
|
undefined
...
@@ -149,6 +147,129 @@ export function getUtils({
...
@@ -149,6 +147,129 @@ export function getUtils({
parsedUrl
.
pathname
!
.
replace
(
new
RegExp
(
`^
${
basePath
}
`
),
''
)
||
'/'
parsedUrl
.
pathname
!
.
replace
(
new
RegExp
(
`^
${
basePath
}
`
),
''
)
||
'/'
}
}
function
getParamsFromRouteMatches
(
req
:
IncomingMessage
,
renderOpts
?:
any
,
detectedLocale
?:
string
)
{
return
getRouteMatcher
(
(
function
()
{
const
{
groups
,
routeKeys
}
=
defaultRouteRegex
!
return
{
re
:
{
// Simulate a RegExp match from the \`req.url\` input
exec
:
(
str
:
string
)
=>
{
const
obj
=
parseQs
(
str
)
// favor named matches if available
const
routeKeyNames
=
Object
.
keys
(
routeKeys
||
{})
const
filterLocaleItem
=
(
val
:
string
|
string
[])
=>
{
if
(
i18n
)
{
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const
isCatchAll
=
Array
.
isArray
(
val
)
const
_val
=
isCatchAll
?
val
[
0
]
:
val
if
(
typeof
_val
===
'string'
&&
i18n
.
locales
.
some
((
item
)
=>
{
if
(
item
.
toLowerCase
()
===
_val
.
toLowerCase
())
{
detectedLocale
=
item
renderOpts
.
locale
=
detectedLocale
return
true
}
return
false
})
)
{
// remove the locale item from the match
if
(
isCatchAll
)
{
;(
val
as
string
[]).
splice
(
0
,
1
)
}
// the value is only a locale item and
// shouldn't be added
return
isCatchAll
?
val
.
length
===
0
:
true
}
}
return
false
}
if
(
routeKeyNames
.
every
((
name
)
=>
obj
[
name
]))
{
return
routeKeyNames
.
reduce
((
prev
,
keyName
)
=>
{
const
paramName
=
routeKeys
?.[
keyName
]
if
(
paramName
&&
!
filterLocaleItem
(
obj
[
keyName
]))
{
prev
[
groups
[
paramName
].
pos
]
=
obj
[
keyName
]
}
return
prev
},
{}
as
any
)
}
return
Object
.
keys
(
obj
).
reduce
((
prev
,
key
)
=>
{
if
(
!
filterLocaleItem
(
obj
[
key
]))
{
return
Object
.
assign
(
prev
,
{
[
key
]:
obj
[
key
],
})
}
return
prev
},
{})
},
},
groups
,
}
})()
as
any
)(
req
.
headers
[
'x-now-route-matches'
]
as
string
)
as
ParsedUrlQuery
}
function
interpolateDynamicPath
(
pathname
:
string
,
params
:
ParsedUrlQuery
)
{
if
(
!
defaultRouteRegex
)
return
pathname
for
(
const
param
of
Object
.
keys
(
defaultRouteRegex
.
groups
))
{
const
{
optional
,
repeat
}
=
defaultRouteRegex
.
groups
[
param
]
let
builtParam
=
`[
${
repeat
?
'...'
:
''
}${
param
}
]`
if
(
optional
)
{
builtParam
=
`[
${
builtParam
}
]`
}
const
paramIdx
=
pathname
!
.
indexOf
(
builtParam
)
if
(
paramIdx
>
-
1
)
{
let
paramValue
:
string
if
(
Array
.
isArray
(
params
[
param
]))
{
paramValue
=
(
params
[
param
]
as
string
[]).
join
(
'/'
)
}
else
{
paramValue
=
params
[
param
]
as
string
}
pathname
=
pathname
.
substr
(
0
,
paramIdx
)
+
encodeURI
(
paramValue
||
''
)
+
pathname
.
substr
(
paramIdx
+
builtParam
.
length
)
}
}
return
pathname
}
function
normalizeVercelUrl
(
req
:
IncomingMessage
,
trustQuery
:
boolean
)
{
// make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing
if
(
pageIsDynamic
&&
trustQuery
&&
defaultRouteRegex
)
{
const
_parsedUrl
=
parseUrl
(
req
.
url
!
,
true
)
delete
(
_parsedUrl
as
any
).
search
for
(
const
param
of
Object
.
keys
(
defaultRouteRegex
.
groups
))
{
delete
_parsedUrl
.
query
[
param
]
}
req
.
url
=
formatUrl
(
_parsedUrl
)
}
}
function
normalizeDynamicRouteParams
(
params
:
ParsedUrlQuery
)
{
function
normalizeDynamicRouteParams
(
params
:
ParsedUrlQuery
)
{
let
hasValidParams
=
true
let
hasValidParams
=
true
if
(
!
defaultRouteRegex
)
return
{
params
,
hasValidParams
}
if
(
!
defaultRouteRegex
)
return
{
params
,
hasValidParams
}
...
@@ -347,8 +468,11 @@ export function getUtils({
...
@@ -347,8 +468,11 @@ export function getUtils({
handleRewrites
,
handleRewrites
,
handleBasePath
,
handleBasePath
,
defaultRouteRegex
,
defaultRouteRegex
,
normalizeVercelUrl
,
dynamicRouteMatcher
,
dynamicRouteMatcher
,
defaultRouteMatches
,
defaultRouteMatches
,
interpolateDynamicPath
,
getParamsFromRouteMatches
,
normalizeDynamicRouteParams
,
normalizeDynamicRouteParams
,
}
}
}
}
packages/next/build/webpack/plugins/font-stylesheet-gathering-plugin.ts
View file @
e819e00d
...
@@ -7,7 +7,10 @@ import {
...
@@ -7,7 +7,10 @@ import {
}
from
'../../../next-server/server/font-utils'
}
from
'../../../next-server/server/font-utils'
import
postcss
from
'postcss'
import
postcss
from
'postcss'
import
minifier
from
'cssnano-simple'
import
minifier
from
'cssnano-simple'
import
{
OPTIMIZED_FONT_PROVIDERS
}
from
'../../../next-server/lib/constants'
import
{
FONT_MANIFEST
,
OPTIMIZED_FONT_PROVIDERS
,
}
from
'../../../next-server/lib/constants'
// @ts-ignore: TODO: remove ignore when webpack 5 is stable
// @ts-ignore: TODO: remove ignore when webpack 5 is stable
const
{
RawSource
}
=
webpack
.
sources
||
sources
const
{
RawSource
}
=
webpack
.
sources
||
sources
...
@@ -169,7 +172,7 @@ export class FontStylesheetGatheringPlugin {
...
@@ -169,7 +172,7 @@ export class FontStylesheetGatheringPlugin {
})
})
}
}
if
(
!
isWebpack5
)
{
if
(
!
isWebpack5
)
{
compilation
.
assets
[
'font-manifest.json'
]
=
new
RawSource
(
compilation
.
assets
[
FONT_MANIFEST
]
=
new
RawSource
(
JSON
.
stringify
(
this
.
manifestContent
,
null
,
' '
)
JSON
.
stringify
(
this
.
manifestContent
,
null
,
' '
)
)
)
}
}
...
@@ -189,7 +192,7 @@ export class FontStylesheetGatheringPlugin {
...
@@ -189,7 +192,7 @@ export class FontStylesheetGatheringPlugin {
stage
:
webpack
.
Compilation
.
PROCESS_ASSETS_STAGE_ADDITIONS
,
stage
:
webpack
.
Compilation
.
PROCESS_ASSETS_STAGE_ADDITIONS
,
},
},
(
assets
:
any
)
=>
{
(
assets
:
any
)
=>
{
assets
[
'font-manifest.json'
]
=
new
RawSource
(
assets
[
FONT_MANIFEST
]
=
new
RawSource
(
JSON
.
stringify
(
this
.
manifestContent
,
null
,
' '
)
JSON
.
stringify
(
this
.
manifestContent
,
null
,
' '
)
)
)
}
}
...
...
packages/next/next-server/lib/constants.ts
View file @
e819e00d
...
@@ -9,6 +9,7 @@ export const EXPORT_DETAIL = 'export-detail.json'
...
@@ -9,6 +9,7 @@ export const EXPORT_DETAIL = 'export-detail.json'
export
const
PRERENDER_MANIFEST
=
'prerender-manifest.json'
export
const
PRERENDER_MANIFEST
=
'prerender-manifest.json'
export
const
ROUTES_MANIFEST
=
'routes-manifest.json'
export
const
ROUTES_MANIFEST
=
'routes-manifest.json'
export
const
IMAGES_MANIFEST
=
'images-manifest.json'
export
const
IMAGES_MANIFEST
=
'images-manifest.json'
export
const
SERVER_FILES_MANIFEST
=
'required-server-files.json'
export
const
DEV_CLIENT_PAGES_MANIFEST
=
'_devPagesManifest.json'
export
const
DEV_CLIENT_PAGES_MANIFEST
=
'_devPagesManifest.json'
export
const
REACT_LOADABLE_MANIFEST
=
'react-loadable-manifest.json'
export
const
REACT_LOADABLE_MANIFEST
=
'react-loadable-manifest.json'
export
const
FONT_MANIFEST
=
'font-manifest.json'
export
const
FONT_MANIFEST
=
'font-manifest.json'
...
...
packages/next/next-server/server/next-server.ts
View file @
e819e00d
...
@@ -85,6 +85,7 @@ import * as Log from '../../build/output/log'
...
@@ -85,6 +85,7 @@ import * as Log from '../../build/output/log'
import
{
imageOptimizer
}
from
'./image-optimizer'
import
{
imageOptimizer
}
from
'./image-optimizer'
import
{
detectDomainLocale
}
from
'../lib/i18n/detect-domain-locale'
import
{
detectDomainLocale
}
from
'../lib/i18n/detect-domain-locale'
import
cookie
from
'next/dist/compiled/cookie'
import
cookie
from
'next/dist/compiled/cookie'
import
{
getUtils
}
from
'../../build/webpack/loaders/next-serverless-loader/utils'
const
getCustomRouteMatcher
=
pathMatch
(
true
)
const
getCustomRouteMatcher
=
pathMatch
(
true
)
...
@@ -132,6 +133,7 @@ export default class Server {
...
@@ -132,6 +133,7 @@ export default class Server {
serverBuildDir
:
string
serverBuildDir
:
string
pagesManifest
?:
PagesManifest
pagesManifest
?:
PagesManifest
buildId
:
string
buildId
:
string
minimalMode
:
boolean
renderOpts
:
{
renderOpts
:
{
poweredByHeader
:
boolean
poweredByHeader
:
boolean
buildId
:
string
buildId
:
string
...
@@ -164,8 +166,9 @@ export default class Server {
...
@@ -164,8 +166,9 @@ export default class Server {
quiet
=
false
,
quiet
=
false
,
conf
=
null
,
conf
=
null
,
dev
=
false
,
dev
=
false
,
minimalMode
=
false
,
customServer
=
true
,
customServer
=
true
,
}:
ServerConstructor
=
{})
{
}:
ServerConstructor
&
{
minimalMode
?:
boolean
}
=
{})
{
this
.
dir
=
resolve
(
dir
)
this
.
dir
=
resolve
(
dir
)
this
.
quiet
=
quiet
this
.
quiet
=
quiet
const
phase
=
this
.
currentPhase
()
const
phase
=
this
.
currentPhase
()
...
@@ -187,6 +190,7 @@ export default class Server {
...
@@ -187,6 +190,7 @@ export default class Server {
}
=
this
.
nextConfig
}
=
this
.
nextConfig
this
.
buildId
=
this
.
readBuildId
()
this
.
buildId
=
this
.
readBuildId
()
this
.
minimalMode
=
minimalMode
this
.
renderOpts
=
{
this
.
renderOpts
=
{
poweredByHeader
:
this
.
nextConfig
.
poweredByHeader
,
poweredByHeader
:
this
.
nextConfig
.
poweredByHeader
,
...
@@ -255,8 +259,8 @@ export default class Server {
...
@@ -255,8 +259,8 @@ export default class Server {
this
.
_isLikeServerless
?
SERVERLESS_DIRECTORY
:
SERVER_DIRECTORY
,
this
.
_isLikeServerless
?
SERVERLESS_DIRECTORY
:
SERVER_DIRECTORY
,
'pages'
'pages'
),
),
flushToDisk
:
this
.
nextConfig
.
experimental
.
sprFlushToDisk
,
locales
:
this
.
nextConfig
.
i18n
?.
locales
,
locales
:
this
.
nextConfig
.
i18n
?.
locales
,
flushToDisk
:
!
minimalMode
&&
this
.
nextConfig
.
experimental
.
sprFlushToDisk
,
})
})
/**
/**
...
@@ -451,6 +455,84 @@ export default class Server {
...
@@ -451,6 +455,84 @@ export default class Server {
defaultLocale
defaultLocale
}
}
if
(
this
.
minimalMode
&&
req
.
headers
[
'x-matched-path'
]
&&
typeof
req
.
headers
[
'x-matched-path'
]
===
'string'
)
{
const
reqUrlIsDataUrl
=
req
.
url
?.
includes
(
'/_next/data'
)
const
matchedPathIsDataUrl
=
req
.
headers
[
'x-matched-path'
]?.
includes
(
'/_next/data'
)
const
isDataUrl
=
reqUrlIsDataUrl
||
matchedPathIsDataUrl
let
parsedPath
=
parseUrl
(
isDataUrl
?
req
.
url
!
:
(
req
.
headers
[
'x-matched-path'
]
as
string
),
true
)
const
{
pathname
,
query
}
=
parsedPath
let
matchedPathname
=
pathname
as
string
const
matchedPathnameNoExt
=
isDataUrl
?
matchedPathname
.
replace
(
/
\.
json$/
,
''
)
:
matchedPathname
// interpolate dynamic params and normalize URL if needed
if
(
isDynamicRoute
(
matchedPathnameNoExt
))
{
const
utils
=
getUtils
({
pageIsDynamic
:
true
,
page
:
matchedPathnameNoExt
,
i18n
:
this
.
nextConfig
.
i18n
,
basePath
:
this
.
nextConfig
.
basePath
,
rewrites
:
this
.
customRoutes
.
rewrites
,
})
let
params
:
ParsedUrlQuery
|
false
=
{}
const
paramsResult
=
utils
.
normalizeDynamicRouteParams
({
...
parsedUrl
.
query
,
...
query
,
})
if
(
paramsResult
.
hasValidParams
)
{
params
=
paramsResult
.
params
}
else
if
(
req
.
headers
[
'x-now-route-matches'
])
{
const
opts
:
Record
<
string
,
string
>
=
{}
params
=
utils
.
getParamsFromRouteMatches
(
req
,
opts
,
(
parsedUrl
.
query
.
__nextLocale
as
string
|
undefined
)
||
''
)
if
(
opts
.
locale
)
{
parsedUrl
.
query
.
__nextLocale
=
opts
.
locale
}
}
else
{
params
=
utils
.
dynamicRouteMatcher
!
(
matchedPathname
)
}
if
(
params
)
{
matchedPathname
=
utils
.
interpolateDynamicPath
(
matchedPathname
,
params
)
req
.
url
=
utils
.
interpolateDynamicPath
(
req
.
url
!
,
params
)
}
if
(
reqUrlIsDataUrl
&&
matchedPathIsDataUrl
)
{
req
.
url
=
formatUrl
({
...
parsedPath
,
pathname
:
matchedPathname
,
})
}
Object
.
assign
(
parsedUrl
.
query
,
params
)
utils
.
normalizeVercelUrl
(
req
,
true
)
}
parsedUrl
.
pathname
=
`
${
basePath
||
''
}${
parsedUrl
.
query
.
__nextLocale
||
''
}${
matchedPathname
}
`
}
res
.
statusCode
=
200
res
.
statusCode
=
200
try
{
try
{
return
await
this
.
run
(
req
,
res
,
parsedUrl
)
return
await
this
.
run
(
req
,
res
,
parsedUrl
)
...
@@ -717,45 +799,47 @@ export default class Server {
...
@@ -717,45 +799,47 @@ export default class Server {
})
})
}
}
const
redirects
=
this
.
customRoutes
.
redirects
.
map
((
redirect
)
=>
{
const
redirects
=
this
.
minimalMode
const
redirectRoute
=
getCustomRoute
(
redirect
,
'redirect'
)
?
[]
return
{
:
this
.
customRoutes
.
redirects
.
map
((
redirect
)
=>
{
internal
:
redirectRoute
.
internal
,
const
redirectRoute
=
getCustomRoute
(
redirect
,
'redirect'
)
type
:
redirectRoute
.
type
,
return
{
match
:
redirectRoute
.
match
,
internal
:
redirectRoute
.
internal
,
statusCode
:
redirectRoute
.
statusCode
,
type
:
redirectRoute
.
type
,
name
:
`Redirect route
${
redirectRoute
.
source
}
`
,
match
:
redirectRoute
.
match
,
fn
:
async
(
req
,
res
,
params
,
parsedUrl
)
=>
{
statusCode
:
redirectRoute
.
statusCode
,
const
{
parsedDestination
}
=
prepareDestination
(
name
:
`Redirect route
${
redirectRoute
.
source
}
`
,
redirectRoute
.
destination
,
fn
:
async
(
req
,
res
,
params
,
parsedUrl
)
=>
{
params
,
const
{
parsedDestination
}
=
prepareDestination
(
parsedUrl
.
query
,
redirectRoute
.
destination
,
false
params
,
)
parsedUrl
.
query
,
false
)
const
{
query
}
=
parsedDestination
const
{
query
}
=
parsedDestination
delete
(
parsedDestination
as
any
).
query
delete
(
parsedDestination
as
any
).
query
parsedDestination
.
search
=
stringifyQuery
(
req
,
query
)
parsedDestination
.
search
=
stringifyQuery
(
req
,
query
)
const
updatedDestination
=
formatUrl
(
parsedDestination
)
const
updatedDestination
=
formatUrl
(
parsedDestination
)
res
.
setHeader
(
'Location'
,
updatedDestination
)
res
.
setHeader
(
'Location'
,
updatedDestination
)
res
.
statusCode
=
getRedirectStatus
(
redirectRoute
as
Redirect
)
res
.
statusCode
=
getRedirectStatus
(
redirectRoute
as
Redirect
)
// Since IE11 doesn't support the 308 header add backwards
// Since IE11 doesn't support the 308 header add backwards
// compatibility using refresh header
// compatibility using refresh header
if
(
res
.
statusCode
===
308
)
{
if
(
res
.
statusCode
===
308
)
{
res
.
setHeader
(
'Refresh'
,
`0;url=
${
updatedDestination
}
`
)
res
.
setHeader
(
'Refresh'
,
`0;url=
${
updatedDestination
}
`
)
}
}
res
.
end
()
res
.
end
()
return
{
return
{
finished
:
true
,
finished
:
true
,
}
}
},
},
}
as
Route
}
as
Route
})
})
const
rewrites
=
this
.
customRoutes
.
rewrites
.
map
((
rewrite
)
=>
{
const
rewrites
=
this
.
customRoutes
.
rewrites
.
map
((
rewrite
)
=>
{
const
rewriteRoute
=
getCustomRoute
(
rewrite
,
'rewrite'
)
const
rewriteRoute
=
getCustomRoute
(
rewrite
,
'rewrite'
)
...
@@ -1322,7 +1406,7 @@ export default class Server {
...
@@ -1322,7 +1406,7 @@ export default class Server {
}
}
let
ssgCacheKey
=
let
ssgCacheKey
=
isPreviewMode
||
!
isSSG
isPreviewMode
||
!
isSSG
||
this
.
minimalMode
?
undefined
// Preview mode bypasses the cache
?
undefined
// Preview mode bypasses the cache
:
`
${
locale
?
`/
${
locale
}
`
:
''
}${
:
`
${
locale
?
`/
${
locale
}
`
:
''
}${
(
pathname
===
'/'
||
resolvedUrlPathname
===
'/'
)
&&
locale
(
pathname
===
'/'
||
resolvedUrlPathname
===
'/'
)
&&
locale
...
@@ -1505,6 +1589,7 @@ export default class Server {
...
@@ -1505,6 +1589,7 @@ export default class Server {
// getStaticPaths, then finish the data request on the client-side.
// getStaticPaths, then finish the data request on the client-side.
//
//
if
(
if
(
this
.
minimalMode
!==
true
&&
fallbackMode
!==
'blocking'
&&
fallbackMode
!==
'blocking'
&&
ssgCacheKey
&&
ssgCacheKey
&&
!
didRespond
&&
!
didRespond
&&
...
...
test/integration/required-server-files/pages/dynamic/[slug].js
0 → 100644
View file @
e819e00d
import
{
useRouter
}
from
'next/router'
export
const
getServerSideProps
=
({
params
})
=>
{
return
{
props
:
{
hello
:
'world'
,
slug
:
params
.
slug
,
random
:
Math
.
random
(),
},
}
}
export
default
function
Page
(
props
)
{
const
router
=
useRouter
()
return
(
<>
<
p
id
=
"dynamic"
>
dynamic
page
<
/p
>
<
p
id
=
"slug"
>
{
props
.
slug
}
<
/p
>
<
p
id
=
"router"
>
{
JSON
.
stringify
(
router
)}
<
/p
>
<
p
id
=
"props"
>
{
JSON
.
stringify
(
props
)}
<
/p
>
<
/
>
)
}
test/integration/required-server-files/pages/fallback/[slug].js
0 → 100644
View file @
e819e00d
import
{
useRouter
}
from
'next/router'
export
const
getStaticProps
=
({
params
})
=>
{
return
{
props
:
{
hello
:
'world'
,
slug
:
params
.
slug
,
random
:
Math
.
random
(),
},
}
}
export
const
getStaticPaths
=
()
=>
{
return
{
paths
:
[
'/fallback/first'
],
fallback
:
true
,
}
}
export
default
function
Page
(
props
)
{
const
router
=
useRouter
()
return
(
<>
<
p
id
=
"fallback"
>
fallback
page
<
/p
>
<
p
id
=
"slug"
>
{
props
.
slug
}
<
/p
>
<
p
id
=
"router"
>
{
JSON
.
stringify
(
router
)}
<
/p
>
<
p
id
=
"props"
>
{
JSON
.
stringify
(
props
)}
<
/p
>
<
/
>
)
}
test/integration/required-server-files/pages/index.js
0 → 100644
View file @
e819e00d
import
{
useRouter
}
from
'next/router'
export
const
getServerSideProps
=
({
req
})
=>
{
return
{
props
:
{
hello
:
'world'
,
random
:
Math
.
random
(),
},
}
}
export
default
function
Page
(
props
)
{
const
router
=
useRouter
()
return
(
<>
<
p
id
=
"index"
>
index
page
<
/p
>
<
p
id
=
"router"
>
{
JSON
.
stringify
(
router
)}
<
/p
>
<
p
id
=
"props"
>
{
JSON
.
stringify
(
props
)}
<
/p
>
<
/
>
)
}
test/integration/required-server-files/test/index.test.js
0 → 100644
View file @
e819e00d
/* eslint-env jest */
import
http
from
'http'
import
fs
from
'fs-extra'
import
{
join
}
from
'path'
import
cheerio
from
'cheerio'
import
Server
from
'next/dist/next-server/server/next-server'
import
{
fetchViaHTTP
,
findPort
,
nextBuild
,
renderViaHTTP
,
}
from
'next-test-utils'
jest
.
setTimeout
(
1000
*
60
*
2
)
const
appDir
=
join
(
__dirname
,
'..'
)
let
server
let
nextApp
let
appPort
let
buildId
let
requiredFilesManifest
describe
(
'Required Server Files'
,
()
=>
{
beforeAll
(
async
()
=>
{
await
fs
.
remove
(
join
(
appDir
,
'.next'
))
await
nextBuild
(
appDir
)
buildId
=
await
fs
.
readFile
(
join
(
appDir
,
'.next/BUILD_ID'
),
'utf8'
)
requiredFilesManifest
=
await
fs
.
readJSON
(
join
(
appDir
,
'.next/required-server-files.json'
)
)
let
files
=
await
fs
.
readdir
(
join
(
appDir
,
'.next'
))
for
(
const
file
of
files
)
{
if
(
file
===
'server'
||
file
===
'required-server-files.json'
||
requiredFilesManifest
.
files
.
includes
(
join
(
'.next'
,
file
))
)
{
continue
}
console
.
log
(
'removing'
,
join
(
'.next'
,
file
))
await
fs
.
remove
(
join
(
appDir
,
'.next'
,
file
))
}
await
fs
.
rename
(
join
(
appDir
,
'pages'
),
join
(
appDir
,
'pages-bak'
))
nextApp
=
new
Server
({
conf
:
{},
dir
:
appDir
,
quiet
:
false
,
minimalMode
:
true
,
})
appPort
=
await
findPort
()
server
=
http
.
createServer
(
async
(
req
,
res
)
=>
{
try
{
await
nextApp
.
getRequestHandler
()(
req
,
res
)
}
catch
(
err
)
{
console
.
error
(
err
)
res
.
statusCode
=
500
res
.
end
(
'error'
)
}
})
await
new
Promise
((
res
,
rej
)
=>
{
server
.
listen
(
appPort
,
(
err
)
=>
(
err
?
rej
(
err
)
:
res
()))
})
console
.
log
(
`Listening at ::
${
appPort
}
`
)
})
afterAll
(
async
()
=>
{
if
(
server
)
server
.
close
()
await
fs
.
rename
(
join
(
appDir
,
'pages-bak'
),
join
(
appDir
,
'pages'
))
})
it
(
'should output required-server-files manifest correctly'
,
async
()
=>
{
expect
(
requiredFilesManifest
.
version
).
toBe
(
1
)
expect
(
Array
.
isArray
(
requiredFilesManifest
.
files
)).
toBe
(
true
)
expect
(
Array
.
isArray
(
requiredFilesManifest
.
ignore
)).
toBe
(
true
)
expect
(
requiredFilesManifest
.
files
.
length
).
toBeGreaterThan
(
0
)
expect
(
requiredFilesManifest
.
ignore
.
length
).
toBeGreaterThan
(
0
)
expect
(
typeof
requiredFilesManifest
.
config
.
configFile
).
toBe
(
'undefined'
)
expect
(
typeof
requiredFilesManifest
.
config
.
trailingSlash
).
toBe
(
'boolean'
)
for
(
const
file
of
requiredFilesManifest
.
files
)
{
console
.
log
(
'checking'
,
file
)
expect
(
await
fs
.
exists
(
join
(
appDir
,
file
))).
toBe
(
true
)
}
})
it
(
'should render SSR page correctly'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/'
)
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#index'
).
text
()).
toBe
(
'index page'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
'/'
)
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#index'
).
text
()).
toBe
(
'index page'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
})
it
(
'should render dynamic SSR page correctly'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/dynamic/first'
)
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#dynamic'
).
text
()).
toBe
(
'dynamic page'
)
expect
(
$
(
'#slug'
).
text
()).
toBe
(
'first'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
'/dynamic/second'
)
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#dynamic'
).
text
()).
toBe
(
'dynamic page'
)
expect
(
$2
(
'#slug'
).
text
()).
toBe
(
'second'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
})
it
(
'should render fallback page correctly'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/fallback/first'
)
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#fallback'
).
text
()).
toBe
(
'fallback page'
)
expect
(
$
(
'#slug'
).
text
()).
toBe
(
'first'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
'/fallback/first'
)
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#fallback'
).
text
()).
toBe
(
'fallback page'
)
expect
(
$2
(
'#slug'
).
text
()).
toBe
(
'first'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
const
html3
=
await
renderViaHTTP
(
appPort
,
'/fallback/second'
)
const
$3
=
cheerio
.
load
(
html3
)
const
data3
=
JSON
.
parse
(
$3
(
'#props'
).
text
())
expect
(
$3
(
'#fallback'
).
text
()).
toBe
(
'fallback page'
)
expect
(
$3
(
'#slug'
).
text
()).
toBe
(
'second'
)
expect
(
isNaN
(
data3
.
random
)).
toBe
(
false
)
const
{
pageProps
:
data4
}
=
JSON
.
parse
(
await
renderViaHTTP
(
appPort
,
`/_next/data/
${
buildId
}
/fallback/third.json`
)
)
expect
(
data4
.
hello
).
toBe
(
'world'
)
expect
(
data4
.
slug
).
toBe
(
'third'
)
})
it
(
'should render SSR page correctly with x-matched-path'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/some-other-path'
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/'
,
},
})
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#index'
).
text
()).
toBe
(
'index page'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
'/some-other-path'
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/'
,
},
})
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#index'
).
text
()).
toBe
(
'index page'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
})
it
(
'should render dynamic SSR page correctly with x-matched-path'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/some-other-path'
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/dynamic/[slug]?slug=first'
,
},
})
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#dynamic'
).
text
()).
toBe
(
'dynamic page'
)
expect
(
$
(
'#slug'
).
text
()).
toBe
(
'first'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
'/some-other-path'
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/dynamic/[slug]?slug=second'
,
},
})
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#dynamic'
).
text
()).
toBe
(
'dynamic page'
)
expect
(
$2
(
'#slug'
).
text
()).
toBe
(
'second'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
})
it
(
'should render fallback page correctly with x-matched-path and routes-matches'
,
async
()
=>
{
const
html
=
await
renderViaHTTP
(
appPort
,
'/fallback/first'
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/fallback/first'
,
'x-now-route-matches'
:
'1=first'
,
},
})
const
$
=
cheerio
.
load
(
html
)
const
data
=
JSON
.
parse
(
$
(
'#props'
).
text
())
expect
(
$
(
'#fallback'
).
text
()).
toBe
(
'fallback page'
)
expect
(
$
(
'#slug'
).
text
()).
toBe
(
'first'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
html2
=
await
renderViaHTTP
(
appPort
,
`/fallback/[slug]`
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/fallback/[slug]'
,
'x-now-route-matches'
:
'1=second'
,
},
})
const
$2
=
cheerio
.
load
(
html2
)
const
data2
=
JSON
.
parse
(
$2
(
'#props'
).
text
())
expect
(
$2
(
'#fallback'
).
text
()).
toBe
(
'fallback page'
)
expect
(
$2
(
'#slug'
).
text
()).
toBe
(
'second'
)
expect
(
isNaN
(
data2
.
random
)).
toBe
(
false
)
expect
(
data2
.
random
).
not
.
toBe
(
data
.
random
)
})
it
(
'should return data correctly with x-matched-path'
,
async
()
=>
{
const
res
=
await
fetchViaHTTP
(
appPort
,
`/_next/data/
${
buildId
}
/dynamic/first.json`
,
undefined
,
{
headers
:
{
'x-matched-path'
:
'/dynamic/[slug]?slug=first'
,
},
}
)
const
{
pageProps
:
data
}
=
await
res
.
json
()
expect
(
data
.
slug
).
toBe
(
'first'
)
expect
(
data
.
hello
).
toBe
(
'world'
)
const
res2
=
await
fetchViaHTTP
(
appPort
,
`/_next/data/
${
buildId
}
/fallback/[slug].json`
,
undefined
,
{
headers
:
{
'x-matched-path'
:
`/_next/data/
${
buildId
}
/fallback/[slug].json`
,
'x-now-route-matches'
:
'1=second'
,
},
}
)
const
{
pageProps
:
data2
}
=
await
res2
.
json
()
expect
(
data2
.
slug
).
toBe
(
'second'
)
expect
(
data2
.
hello
).
toBe
(
'world'
)
})
it
(
'should not apply trailingSlash redirect'
,
async
()
=>
{
for
(
const
path
of
[
'/'
,
'/dynamic/another/'
,
'/dynamic/another'
,
'/fallback/first/'
,
'/fallback/first'
,
'/fallback/another/'
,
'/fallback/another'
,
])
{
const
res
=
await
fetchViaHTTP
(
appPort
,
path
,
undefined
,
{
redirect
:
'manual'
,
})
expect
(
res
.
status
).
toBe
(
200
)
}
})
})
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment