Skip to content

Commit ba3a430

Browse files
piehkodiakhq[bot]
andauthored
fix: don't deploy metadata files to CDN (#2104)
* fix: tRaCe * chore: add more metadata files for deletion * refactor: move concrete file removal logic into it's own function * chore: make hidden paths consistent * test: update snapshot and add unit test for file removal * chore: add code comment about timing of metadata files removal * fix: publish 404 and 500 to cdn * test: don't delete BUILD_ID in test env * test: update snapshot * fix: typescript gods * chore: dummy commit * chore: dummy commit2 * chore: dummy commit3 * test: update snapshot * test: use different dedicated env var to skip deleting BUILD_ID * test: update utils.spec.ts assertions * test: keep all the metadata for e2e tests * chore: update comment * perf: delete files concurrently instead of 1 by 1 * chore: update comment --------- Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
1 parent f051e22 commit ba3a430

File tree

9 files changed

+125
-111
lines changed

9 files changed

+125
-111
lines changed

packages/runtime/src/constants.ts

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import destr from 'destr'
2+
13
export const HANDLER_FUNCTION_NAME = '___netlify-handler'
24
export const ODB_FUNCTION_NAME = '___netlify-odb-handler'
35
export const IMAGE_FUNCTION_NAME = '_ipx'
@@ -7,18 +9,29 @@ export const HANDLER_FUNCTION_TITLE = 'Next.js SSR handler'
79
export const ODB_FUNCTION_TITLE = 'Next.js ISR handler'
810
export const IMAGE_FUNCTION_TITLE = 'next/image handler'
911
// These are paths in .next that shouldn't be publicly accessible
10-
export const HIDDEN_PATHS = [
11-
'/cache/*',
12-
'/server/*',
13-
'/serverless/*',
14-
'/trace',
15-
'/traces',
16-
'/routes-manifest.json',
17-
'/build-manifest.json',
18-
'/prerender-manifest.json',
19-
'/react-loadable-manifest.json',
20-
'/BUILD_ID',
21-
]
12+
export const HIDDEN_PATHS = destr(process.env.NEXT_KEEP_METADATA_FILES)
13+
? []
14+
: [
15+
'/cache',
16+
'/server',
17+
'/serverless',
18+
'/trace',
19+
'/traces',
20+
'/routes-manifest.json',
21+
'/build-manifest.json',
22+
'/prerender-manifest.json',
23+
'/react-loadable-manifest.json',
24+
'/BUILD_ID',
25+
'/app-build-manifest.json',
26+
'/app-path-routes-manifest.json',
27+
'/export-marker.json',
28+
'/images-manifest.json',
29+
'/next-server.js.nft.json',
30+
'/package.json',
31+
'/prerender-manifest.js',
32+
'/required-server-files.json',
33+
'/static-manifest.json',
34+
]
2235

2336
export const ODB_FUNCTION_PATH = `/.netlify/builders/${ODB_FUNCTION_NAME}`
2437
export const HANDLER_FUNCTION_PATH = `/.netlify/functions/${HANDLER_FUNCTION_NAME}`

packages/runtime/src/helpers/files.ts

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,26 @@ import { cpus } from 'os'
22

33
import type { NetlifyConfig } from '@netlify/build'
44
import { yellowBright } from 'chalk'
5-
import { existsSync, readJson, move, copy, writeJson, readFile, writeFile, ensureDir, readFileSync } from 'fs-extra'
5+
import {
6+
existsSync,
7+
readJson,
8+
move,
9+
copy,
10+
writeJson,
11+
readFile,
12+
writeFile,
13+
ensureDir,
14+
readFileSync,
15+
remove,
16+
} from 'fs-extra'
617
import globby from 'globby'
718
import { PrerenderManifest } from 'next/dist/build'
819
import { outdent } from 'outdent'
920
import pLimit from 'p-limit'
1021
import { join, resolve, dirname } from 'pathe'
1122
import slash from 'slash'
1223

13-
import { MINIMUM_REVALIDATE_SECONDS, DIVIDER } from '../constants'
24+
import { MINIMUM_REVALIDATE_SECONDS, DIVIDER, HIDDEN_PATHS } from '../constants'
1425

1526
import { NextConfig } from './config'
1627
import { loadPrerenderManifest } from './edge'
@@ -138,8 +149,8 @@ export const moveStaticPages = async ({
138149
console.warn('Error moving file', source, error)
139150
}
140151
}
141-
// Move all static files, except error documents and nft manifests
142-
const pages = await globby(['{app,pages}/**/*.{html,json,rsc}', '!**/(500|404|*.js.nft).{html,json}'], {
152+
// Move all static files, except nft manifests
153+
const pages = await globby(['{app,pages}/**/*.{html,json,rsc}', '!**/*.js.nft.{html,json}'], {
143154
cwd: outputDir,
144155
dot: true,
145156
})
@@ -467,3 +478,15 @@ export const movePublicFiles = async ({
467478
await copy(publicDir, `${publish}${basePath}/`)
468479
}
469480
}
481+
482+
export const removeMetadataFiles = async (publish: string) => {
483+
// Limit concurrent deletions to number of cpus or 2 if there is only 1
484+
const limit = pLimit(Math.max(2, cpus().length))
485+
486+
const removePromises = HIDDEN_PATHS.map((HIDDEN_PATH) => {
487+
const pathToDelete = join(publish, HIDDEN_PATH)
488+
return limit(() => remove(pathToDelete))
489+
})
490+
491+
await Promise.all(removePromises)
492+
}

packages/runtime/src/helpers/redirects.ts

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import type { PrerenderManifest, SsgRoute } from 'next/dist/build'
77
import { outdent } from 'outdent'
88
import { join } from 'pathe'
99

10-
import { HANDLER_FUNCTION_PATH, HIDDEN_PATHS, ODB_FUNCTION_PATH } from '../constants'
10+
import { HANDLER_FUNCTION_PATH, ODB_FUNCTION_PATH } from '../constants'
1111

1212
import { isAppDirRoute, loadAppPathRoutesManifest } from './edge'
1313
import { getMiddleware } from './files'
@@ -27,14 +27,6 @@ import {
2727
const matchesMiddleware = (middleware: Array<string>, route: string): boolean =>
2828
middleware.some((middlewarePath) => route.startsWith(middlewarePath))
2929

30-
const generateHiddenPathRedirects = ({ basePath }: Pick<NextConfig, 'basePath'>): NetlifyConfig['redirects'] =>
31-
HIDDEN_PATHS.map((path) => ({
32-
from: `${basePath}${path}`,
33-
to: '/404.html',
34-
status: 404,
35-
force: true,
36-
}))
37-
3830
const generateLocaleRedirects = ({
3931
i18n,
4032
basePath,
@@ -281,8 +273,6 @@ export const generateRedirects = async ({
281273
join(netlifyConfig.build.publish, 'routes-manifest.json'),
282274
)
283275

284-
netlifyConfig.redirects.push(...generateHiddenPathRedirects({ basePath }))
285-
286276
if (i18n && i18n.localeDetection !== false) {
287277
netlifyConfig.redirects.push(...generateLocaleRedirects({ i18n, basePath, trailingSlash }))
288278
}

packages/runtime/src/helpers/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ export const redirectsForNext404Route = ({
170170
}): NetlifyConfig['redirects'] =>
171171
netlifyRoutesForNextRoute({ route, buildId, i18n }).map(({ redirect, locale }) => ({
172172
from: `${basePath}${redirect}`,
173-
to: locale ? `${basePath}/server/pages/${locale}/404.html` : `${basePath}/server/pages/404.html`,
173+
to: locale ? `${basePath}/${locale}/404.html` : `${basePath}/404.html`,
174174
status: 404,
175175
force,
176176
}))

packages/runtime/src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
} from './helpers/config'
1818
import { onPreDev } from './helpers/dev'
1919
import { writeEdgeFunctions, loadMiddlewareManifest, cleanupEdgeFunctions } from './helpers/edge'
20-
import { moveStaticPages, movePublicFiles, patchNextFiles } from './helpers/files'
20+
import { moveStaticPages, movePublicFiles, patchNextFiles, removeMetadataFiles } from './helpers/files'
2121
import { splitApiRoutes } from './helpers/flags'
2222
import {
2323
generateFunctions,
@@ -254,6 +254,12 @@ const plugin: NetlifyPlugin = {
254254
warnForProblematicUserRewrites({ basePath, redirects })
255255
warnForRootRedirects({ appDir })
256256
await warnOnApiRoutes({ FUNCTIONS_DIST })
257+
258+
// we are removing metadata files from Publish directory
259+
// we have to do this after functions were bundled as bundling still
260+
// require those files, but we don't want to publish them
261+
await removeMetadataFiles(publish)
262+
257263
if (experimental?.appDir) {
258264
console.log(
259265
'🧪 Thank you for testing "appDir" support on Netlify. For known issues and to give feedback, visit https://ntl.fyi/next-13-feedback',

0 commit comments

Comments
 (0)