@netlify/plugin-nextjs 4.0.0-beta.1 → 4.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  # Essential Next.js Build Plugin (beta)
4
4
 
5
-
6
- :warning: This is the beta version of the Essential Next.js plugin. For the stable version, see [Essential Next.js plugin v3](https://github.com/netlify/netlify-plugin-nextjs/tree/v3#readme) :warning:
5
+ :warning: This is the beta version of the Essential Next.js plugin. For the stable version, refer to
6
+ [Essential Next.js plugin v3](https://github.com/netlify/netlify-plugin-nextjs/tree/v3#readme) :warning:
7
7
 
8
8
  <p align="center">
9
9
  <a aria-label="npm version" href="https://www.npmjs.com/package/@netlify/plugin-nextjs">
@@ -14,15 +14,21 @@
14
14
  </a>
15
15
  </p>
16
16
 
17
+ ## What's new in this version
17
18
 
18
- ## Installing the beta
19
+ Version 4 is a complete rewrite of the Essential Next.js plugin. For full details of everything that's new, check out
20
+ [the v4 release notes](https://github.com/netlify/netlify-plugin-nextjs/blob/main/docs/release-notes/v4.md)
19
21
 
22
+ ## Installing the beta
20
23
 
21
24
  - Install the module:
25
+
22
26
  ```shell
23
27
  npm install -D @netlify/plugin-nextjs@beta
24
28
  ```
25
- - Change the `publish` directory to `.next` and add the plugin to `netlify.toml` if not already installed:
29
+
30
+ - Change the `publish` directory to `.next` and add the plugin to `netlify.toml` if not already installed:
31
+
26
32
  ```toml
27
33
  [build]
28
34
  publish = ".next"
@@ -31,4 +37,27 @@ publish = ".next"
31
37
  package = "@netlify/plugin-nextjs"
32
38
  ```
33
39
 
34
- If you previously set `target: "serverless"` in your `next.config.js` this is no longer needed and can be removed.
40
+ If you previously set a custom `distDir` in your `next.config.js`, or set `node_bundler` or `external_node_modules` in
41
+ your `netlify.toml` these are no longer needed and can be removed.
42
+
43
+ The `serverless` and `experimental-serverless-trace` targets are deprecated in Next 12, and all builds with this plugin
44
+ will now use the default `server` target. If you previously set the target in your `next.config.js`, you should remove
45
+ it.
46
+
47
+ If you are using a monorepo you will need to change `publish` to point to the full path to the built `.next` directory,
48
+ which may be in a subdirectory. If you have changed your `distDir` then it will need to match that.
49
+
50
+ If you are using Nx, then you will need to point `publish` to the folder inside `dist`, e.g. `dist/apps/myapp/.next`.
51
+
52
+ If you currently use redirects or rewrites on your site, see
53
+ [the Rewrites and Redirects guide](https://github.com/netlify/netlify-plugin-nextjs/blob/main/docs/redirects-rewrites.md)
54
+ for information on changes to how they are handled in this version.
55
+
56
+ If you want to use Next 12's beta Middleware feature, this will mostly work as expected but please
57
+ [read the docs on some caveats and workarounds](https://github.com/netlify/netlify-plugin-nextjs/blob/main/docs/middleware.md)
58
+ that are currently needed.
59
+
60
+ ## Beta feedback
61
+
62
+ Please share any thoughts, feedback or questions about the beta
63
+ [in our discussion](https://github.com/netlify/netlify-plugin-nextjs/discussions/706).
package/lib/.DS_Store ADDED
Binary file
package/lib/constants.js CHANGED
@@ -1,8 +1,6 @@
1
- const destr = require('destr');
2
1
  const HANDLER_FUNCTION_NAME = '___netlify-handler';
3
2
  const ODB_FUNCTION_NAME = '___netlify-odb-handler';
4
3
  const IMAGE_FUNCTION_NAME = '_ipx';
5
- const ODB_PATH = destr(process.env.EXPERIMENTAL_PERSISTENT_BUILDERS) ? 'builders' : 'functions';
6
4
  // These are paths in .next that shouldn't be publicly accessible
7
5
  const HIDDEN_PATHS = [
8
6
  '/cache/*',
@@ -20,5 +18,4 @@ module.exports = {
20
18
  IMAGE_FUNCTION_NAME,
21
19
  HANDLER_FUNCTION_NAME,
22
20
  ODB_FUNCTION_NAME,
23
- ODB_PATH,
24
21
  };
@@ -1,11 +1,14 @@
1
- // @ts-check
2
- const { join } = require('path');
3
- const { readJSON } = require('fs-extra');
1
+ /* eslint-disable max-lines */
2
+ const { yellowBright } = require('chalk');
3
+ const { readJSON, existsSync } = require('fs-extra');
4
+ const { outdent } = require('outdent');
5
+ const { join, dirname, relative } = require('pathe');
6
+ const slash = require('slash');
4
7
  const defaultFailBuild = (message, { error }) => {
5
8
  throw new Error(`${message}\n${error && error.stack}`);
6
9
  };
7
- const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, HIDDEN_PATHS, ODB_PATH } = require('../constants');
8
- const ODB_FUNCTION_PATH = `/.netlify/${ODB_PATH}/${ODB_FUNCTION_NAME}`;
10
+ const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, HIDDEN_PATHS } = require('../constants');
11
+ const ODB_FUNCTION_PATH = `/.netlify/builders/${ODB_FUNCTION_NAME}`;
9
12
  const HANDLER_FUNCTION_PATH = `/.netlify/functions/${HANDLER_FUNCTION_NAME}`;
10
13
  const CATCH_ALL_REGEX = /\/\[\.{3}(.*)](.json)?$/;
11
14
  const OPTIONAL_CATCH_ALL_REGEX = /\/\[{2}\.{3}(.*)]{2}(.json)?$/;
@@ -38,58 +41,134 @@ const getNetlifyRoutes = (nextRoute) => {
38
41
  return netlifyRoutes;
39
42
  };
40
43
  exports.generateRedirects = async ({ netlifyConfig, basePath, i18n }) => {
41
- const { dynamicRoutes } = await readJSON(join(netlifyConfig.build.publish, 'prerender-manifest.json'));
42
- const redirects = [];
44
+ const { dynamicRoutes, routes: staticRoutes } = await readJSON(join(netlifyConfig.build.publish, 'prerender-manifest.json'));
43
45
  netlifyConfig.redirects.push(...HIDDEN_PATHS.map((path) => ({
44
46
  from: `${basePath}${path}`,
45
47
  to: '/404.html',
46
48
  status: 404,
47
49
  force: true,
48
50
  })));
51
+ const dataRedirects = [];
52
+ const pageRedirects = [];
53
+ const isrRedirects = [];
54
+ let hasIsr = false;
49
55
  const dynamicRouteEntries = Object.entries(dynamicRoutes);
50
- dynamicRouteEntries.sort((a, b) => a[0].localeCompare(b[0]));
56
+ const staticRouteEntries = Object.entries(staticRoutes);
57
+ staticRouteEntries.forEach(([route, { dataRoute, initialRevalidateSeconds }]) => {
58
+ // Only look for revalidate as we need to rewrite these to SSR rather than ODB
59
+ if (initialRevalidateSeconds === false) {
60
+ // These can be ignored, as they're static files handled by the CDN
61
+ return;
62
+ }
63
+ if (i18n.defaultLocale && route.startsWith(`/${i18n.defaultLocale}/`)) {
64
+ route = route.slice(i18n.defaultLocale.length + 1);
65
+ }
66
+ hasIsr = true;
67
+ isrRedirects.push(...getNetlifyRoutes(dataRoute), ...getNetlifyRoutes(route));
68
+ });
51
69
  dynamicRouteEntries.forEach(([route, { dataRoute, fallback }]) => {
52
70
  // Add redirects if fallback is "null" (aka blocking) or true/a string
53
71
  if (fallback === false) {
54
72
  return;
55
73
  }
56
- redirects.push(...getNetlifyRoutes(route), ...getNetlifyRoutes(dataRoute));
74
+ pageRedirects.push(...getNetlifyRoutes(route));
75
+ dataRedirects.push(...getNetlifyRoutes(dataRoute));
57
76
  });
58
77
  if (i18n) {
59
78
  netlifyConfig.redirects.push({ from: `${basePath}/:locale/_next/static/*`, to: `/static/:splat`, status: 200 });
60
79
  }
61
80
  // This is only used in prod, so dev uses `next dev` directly
62
- netlifyConfig.redirects.push({ from: `${basePath}/_next/static/*`, to: `/static/:splat`, status: 200 }, {
81
+ netlifyConfig.redirects.push(
82
+ // Static files are in `static`
83
+ { from: `${basePath}/_next/static/*`, to: `/static/:splat`, status: 200 },
84
+ // API routes always need to be served from the regular function
85
+ {
86
+ from: `${basePath}/api`,
87
+ to: HANDLER_FUNCTION_PATH,
88
+ status: 200,
89
+ }, {
90
+ from: `${basePath}/api/*`,
91
+ to: HANDLER_FUNCTION_PATH,
92
+ status: 200,
93
+ },
94
+ // Preview mode gets forced to the function, to bypess pre-rendered pages
95
+ {
63
96
  from: `${basePath}/*`,
64
97
  to: HANDLER_FUNCTION_PATH,
65
98
  status: 200,
66
- force: true,
67
99
  conditions: { Cookie: ['__prerender_bypass', '__next_preview_data'] },
68
- }, ...redirects.map((redirect) => ({
100
+ force: true,
101
+ },
102
+ // ISR redirects are handled by the regular function. Forced to avoid pre-rendered pages
103
+ ...isrRedirects.map((redirect) => ({
104
+ from: `${basePath}${redirect}`,
105
+ to: HANDLER_FUNCTION_PATH,
106
+ status: 200,
107
+ force: true,
108
+ })),
109
+ // These are pages with fallback set, which need an ODB
110
+ // Data redirects go first, to avoid conflict with splat redirects
111
+ ...dataRedirects.map((redirect) => ({
112
+ from: `${basePath}${redirect}`,
113
+ to: ODB_FUNCTION_PATH,
114
+ status: 200,
115
+ })),
116
+ // ...then all the other fallback pages
117
+ ...pageRedirects.map((redirect) => ({
69
118
  from: `${basePath}${redirect}`,
70
119
  to: ODB_FUNCTION_PATH,
71
120
  status: 200,
72
- })), { from: `${basePath}/*`, to: HANDLER_FUNCTION_PATH, status: 200 });
121
+ })),
122
+ // Everything else is handled by the regular function
123
+ { from: `${basePath}/*`, to: HANDLER_FUNCTION_PATH, status: 200 });
124
+ if (hasIsr) {
125
+ console.log(yellowBright(outdent `
126
+ You have some pages that use ISR (pages that use getStaticProps with revalidate set), which is not currently fully-supported by this plugin. Be aware that results may be unreliable.
127
+ `));
128
+ }
73
129
  };
74
130
  exports.getNextConfig = async function getNextConfig({ publish, failBuild = defaultFailBuild }) {
75
131
  try {
76
- const { config, appDir } = await readJSON(join(publish, 'required-server-files.json'));
132
+ const { config, appDir, ignore } = await readJSON(join(publish, 'required-server-files.json'));
77
133
  if (!config) {
78
134
  return failBuild('Error loading your Next config');
79
135
  }
80
- return { ...config, appDir };
136
+ return { ...config, appDir, ignore };
81
137
  }
82
138
  catch (error) {
83
139
  return failBuild('Error loading your Next config', { error });
84
140
  }
85
141
  };
86
- exports.configureHandlerFunctions = ({ netlifyConfig, publish }) => {
87
- ;
142
+ const resolveModuleRoot = (moduleName) => {
143
+ try {
144
+ return dirname(relative(process.cwd(), require.resolve(`${moduleName}/package.json`, { paths: [process.cwd()] })));
145
+ }
146
+ catch (error) {
147
+ return null;
148
+ }
149
+ };
150
+ const DEFAULT_EXCLUDED_MODULES = ['sharp', 'electron'];
151
+ exports.configureHandlerFunctions = ({ netlifyConfig, publish, ignore = [] }) => {
152
+ var _a;
153
+ /* eslint-disable no-underscore-dangle */
154
+ (_a = netlifyConfig.functions)._ipx || (_a._ipx = {});
155
+ netlifyConfig.functions._ipx.node_bundler = 'nft';
88
156
  [HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME].forEach((functionName) => {
89
157
  var _a, _b;
90
158
  (_a = netlifyConfig.functions)[functionName] || (_a[functionName] = { included_files: [], external_node_modules: [] });
91
159
  netlifyConfig.functions[functionName].node_bundler = 'nft';
92
160
  (_b = netlifyConfig.functions[functionName]).included_files || (_b.included_files = []);
93
- netlifyConfig.functions[functionName].included_files.push(`${publish}/server/**`, `${publish}/serverless/**`, `${publish}/*.json`, `${publish}/BUILD_ID`, '!node_modules/@next/swc-*/**/*', '!node_modules/next/dist/compiled/@ampproject/toolbox-optimizer/**/*', '!node_modules/next/dist/pages/**/*', `!node_modules/next/dist/server/lib/squoosh/**/*.wasm`, `!node_modules/next/dist/next-server/server/lib/squoosh/**/*.wasm`, '!node_modules/next/dist/compiled/webpack/(bundle4|bundle5).js', '!node_modules/react/**/*.development.js', '!node_modules/react-dom/**/*.development.js', '!node_modules/use-subscription/**/*.development.js', '!node_modules/sharp/**/*');
161
+ netlifyConfig.functions[functionName].included_files.push(`${publish}/server/**`, `${publish}/serverless/**`, `${publish}/*.json`, `${publish}/BUILD_ID`, `${publish}/static/chunks/webpack-middleware*.js`, `!${publish}/server/**/*.js.nft.json`, ...ignore.map((path) => `!${slash(path)}`));
162
+ const nextRoot = resolveModuleRoot('next');
163
+ if (nextRoot) {
164
+ netlifyConfig.functions[functionName].included_files.push(`!${nextRoot}/dist/server/lib/squoosh/**/*.wasm`, `!${nextRoot}/dist/next-server/server/lib/squoosh/**/*.wasm`, `!${nextRoot}/dist/compiled/webpack/bundle4.js`, `!${nextRoot}/dist/compiled/webpack/bundle5.js`, `!${nextRoot}/dist/compiled/terser/bundle.min.js`);
165
+ }
166
+ DEFAULT_EXCLUDED_MODULES.forEach((moduleName) => {
167
+ const moduleRoot = resolveModuleRoot(moduleName);
168
+ if (moduleRoot) {
169
+ netlifyConfig.functions[functionName].included_files.push(`!${moduleRoot}/**/*`);
170
+ }
171
+ });
94
172
  });
95
173
  };
174
+ /* eslint-enable max-lines */
@@ -0,0 +1,187 @@
1
+ /* eslint-disable max-lines */
2
+ const { cpus } = require('os');
3
+ const { yellowBright } = require('chalk');
4
+ const { existsSync, readJson, move, cpSync, copy, writeJson } = require('fs-extra');
5
+ const globby = require('globby');
6
+ const { outdent } = require('outdent');
7
+ const pLimit = require('p-limit');
8
+ const { join } = require('pathe');
9
+ const slash = require('slash');
10
+ const TEST_ROUTE = /(|\/)\[[^/]+?](\/|\.html|$)/;
11
+ const isDynamicRoute = (route) => TEST_ROUTE.test(route);
12
+ const stripLocale = (rawPath, locales = []) => {
13
+ const [locale, ...segments] = rawPath.split('/');
14
+ if (locales.includes(locale)) {
15
+ return segments.join('/');
16
+ }
17
+ return rawPath;
18
+ };
19
+ const matchMiddleware = (middleware, filePath) => (middleware === null || middleware === void 0 ? void 0 : middleware.includes('')) ||
20
+ (middleware === null || middleware === void 0 ? void 0 : middleware.find((middlewarePath) => filePath === middlewarePath || filePath === `${middlewarePath}.html` || filePath.startsWith(`${middlewarePath}/`)));
21
+ const matchesRedirect = (file, redirects) => {
22
+ if (!Array.isArray(redirects)) {
23
+ return false;
24
+ }
25
+ return redirects.some((redirect) => {
26
+ if (!redirect.regex || redirect.internal) {
27
+ return false;
28
+ }
29
+ // Strips the extension from the file path
30
+ return new RegExp(redirect.regex).test(`/${file.slice(0, -5)}`);
31
+ });
32
+ };
33
+ const matchesRewrite = (file, rewrites) => {
34
+ if (Array.isArray(rewrites)) {
35
+ return matchesRedirect(file, rewrites);
36
+ }
37
+ if (!Array.isArray(rewrites === null || rewrites === void 0 ? void 0 : rewrites.beforeFiles)) {
38
+ return false;
39
+ }
40
+ return matchesRedirect(file, rewrites.beforeFiles);
41
+ };
42
+ exports.matchesRedirect = matchesRedirect;
43
+ exports.matchesRewrite = matchesRewrite;
44
+ exports.matchMiddleware = matchMiddleware;
45
+ exports.stripLocale = stripLocale;
46
+ exports.isDynamicRoute = isDynamicRoute;
47
+ // eslint-disable-next-line max-lines-per-function
48
+ exports.moveStaticPages = async ({ netlifyConfig, target, i18n }) => {
49
+ console.log('Moving static page files to serve from CDN...');
50
+ const outputDir = join(netlifyConfig.build.publish, target === 'server' ? 'server' : 'serverless');
51
+ const root = join(outputDir, 'pages');
52
+ // Load the middleware manifest so we can check if a file matches it before moving
53
+ let middleware;
54
+ const manifestPath = join(outputDir, 'middleware-manifest.json');
55
+ if (existsSync(manifestPath)) {
56
+ const manifest = await readJson(manifestPath);
57
+ if (manifest === null || manifest === void 0 ? void 0 : manifest.middleware) {
58
+ middleware = Object.keys(manifest.middleware).map((path) => path.slice(1));
59
+ }
60
+ }
61
+ const prerenderManifest = await readJson(join(netlifyConfig.build.publish, 'prerender-manifest.json'));
62
+ const { redirects, rewrites } = await readJson(join(netlifyConfig.build.publish, 'routes-manifest.json'));
63
+ const isrFiles = new Set();
64
+ Object.entries(prerenderManifest.routes).forEach(([route, { initialRevalidateSeconds }]) => {
65
+ if (initialRevalidateSeconds) {
66
+ // Find all files used by ISR routes
67
+ const trimmedPath = route.slice(1);
68
+ isrFiles.add(`${trimmedPath}.html`);
69
+ isrFiles.add(`${trimmedPath}.json`);
70
+ }
71
+ });
72
+ const files = [];
73
+ const moveFile = async (file) => {
74
+ const source = join(root, file);
75
+ files.push(file);
76
+ const dest = join(netlifyConfig.build.publish, file);
77
+ try {
78
+ await move(source, dest);
79
+ }
80
+ catch (error) {
81
+ console.warn('Error moving file', source, error);
82
+ }
83
+ };
84
+ // Move all static files, except error documents and nft manifests
85
+ const pages = await globby(['**/*.{html,json}', '!**/(500|404|*.js.nft).{html,json}'], {
86
+ cwd: root,
87
+ dot: true,
88
+ });
89
+ const matchingMiddleware = new Set();
90
+ const matchedPages = new Set();
91
+ const matchedRedirects = new Set();
92
+ const matchedRewrites = new Set();
93
+ // Limit concurrent file moves to number of cpus or 2 if there is only 1
94
+ const limit = pLimit(Math.max(2, cpus().length));
95
+ const promises = pages.map(async (rawPath) => {
96
+ const filePath = slash(rawPath);
97
+ // Don't move ISR files, as they're used for the first request
98
+ if (isrFiles.has(filePath)) {
99
+ return;
100
+ }
101
+ if (isDynamicRoute(filePath)) {
102
+ return;
103
+ }
104
+ if (matchesRedirect(filePath, redirects)) {
105
+ matchedRedirects.add(filePath);
106
+ return;
107
+ }
108
+ if (matchesRewrite(filePath, rewrites)) {
109
+ matchedRewrites.add(filePath);
110
+ return;
111
+ }
112
+ // Middleware matches against the unlocalised path
113
+ const unlocalizedPath = stripLocale(rawPath, i18n === null || i18n === void 0 ? void 0 : i18n.locales);
114
+ const middlewarePath = matchMiddleware(middleware, unlocalizedPath);
115
+ // If a file matches middleware it can't be offloaded to the CDN, and needs to stay at the origin to be served by next/server
116
+ if (middlewarePath) {
117
+ matchingMiddleware.add(middlewarePath);
118
+ matchedPages.add(rawPath);
119
+ return;
120
+ }
121
+ return limit(moveFile, filePath);
122
+ });
123
+ await Promise.all(promises);
124
+ console.log(`Moved ${files.length} files`);
125
+ if (matchedPages.size !== 0) {
126
+ console.log(yellowBright(outdent `
127
+ Skipped moving ${matchedPages.size} ${matchedPages.size === 1 ? 'file because it matches' : 'files because they match'} middleware, so cannot be deployed to the CDN and will be served from the origin instead.
128
+ This is fine, but we're letting you know because it may not be what you expect.
129
+ `));
130
+ console.log(outdent `
131
+ The following middleware matched statically-rendered pages:
132
+
133
+ ${yellowBright([...matchingMiddleware].map((mid) => `- /${mid}/_middleware`).join('\n'))}
134
+
135
+ ────────────────────────────────────────────────────────────────
136
+ `);
137
+ // There could potentially be thousands of matching pages, so we don't want to spam the console with this
138
+ if (matchedPages.size < 50) {
139
+ console.log(outdent `
140
+ The following files matched middleware and were not moved to the CDN:
141
+
142
+ ${yellowBright([...matchedPages].map((mid) => `- ${mid}`).join('\n'))}
143
+
144
+ ────────────────────────────────────────────────────────────────
145
+ `);
146
+ }
147
+ }
148
+ if (matchedRedirects.size !== 0 || matchedRewrites.size !== 0) {
149
+ console.log(yellowBright(outdent `
150
+ Skipped moving ${matchedRedirects.size + matchedRewrites.size} files because they match redirects or beforeFiles rewrites, so cannot be deployed to the CDN and will be served from the origin instead.
151
+ `));
152
+ if (matchedRedirects.size < 50 && matchedRedirects.size !== 0) {
153
+ console.log(outdent `
154
+ The following files matched redirects and were not moved to the CDN:
155
+
156
+ ${yellowBright([...matchedRedirects].map((mid) => `- ${mid}`).join('\n'))}
157
+
158
+ ────────────────────────────────────────────────────────────────
159
+ `);
160
+ }
161
+ if (matchedRewrites.size < 50 && matchedRewrites.size !== 0) {
162
+ console.log(outdent `
163
+ The following files matched beforeFiles rewrites and were not moved to the CDN:
164
+
165
+ ${yellowBright([...matchedRewrites].map((mid) => `- ${mid}`).join('\n'))}
166
+
167
+ ────────────────────────────────────────────────────────────────
168
+ `);
169
+ }
170
+ }
171
+ // Write the manifest for use in the serverless functions
172
+ await writeJson(join(netlifyConfig.build.publish, 'static-manifest.json'), files);
173
+ if (i18n === null || i18n === void 0 ? void 0 : i18n.defaultLocale) {
174
+ // Copy the default locale into the root
175
+ const defaultLocaleDir = join(netlifyConfig.build.publish, i18n.defaultLocale);
176
+ if (existsSync(defaultLocaleDir)) {
177
+ await copy(defaultLocaleDir, `${netlifyConfig.build.publish}/`);
178
+ }
179
+ }
180
+ };
181
+ exports.movePublicFiles = async ({ appDir, publish }) => {
182
+ const publicDir = join(appDir, 'public');
183
+ if (existsSync(publicDir)) {
184
+ await copy(publicDir, `${publish}/`);
185
+ }
186
+ };
187
+ /* eslint-enable max-lines */
@@ -1,6 +1,6 @@
1
- const { join, relative } = require('path');
2
1
  const { copyFile, ensureDir, writeFile, writeJSON } = require('fs-extra');
3
- const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, IMAGE_FUNCTION_NAME, ODB_PATH } = require('../constants');
2
+ const { join, relative } = require('pathe');
3
+ const { HANDLER_FUNCTION_NAME, ODB_FUNCTION_NAME, IMAGE_FUNCTION_NAME } = require('../constants');
4
4
  const getHandler = require('../templates/getHandler');
5
5
  const { getPageResolver } = require('../templates/getPageResolver');
6
6
  const DEFAULT_FUNCTIONS_SRC = 'netlify/functions';
@@ -14,6 +14,7 @@ exports.generateFunctions = async ({ FUNCTIONS_SRC = DEFAULT_FUNCTIONS_SRC, INTE
14
14
  await ensureDir(join(functionsDir, func));
15
15
  await writeFile(join(functionsDir, func, `${func}.js`), handlerSource);
16
16
  await copyFile(bridgeFile, join(functionsDir, func, 'bridge.js'));
17
+ await copyFile(join(__dirname, '..', '..', 'lib', 'templates', 'handlerUtils.js'), join(functionsDir, func, 'handlerUtils.js'));
17
18
  };
18
19
  await writeHandler(HANDLER_FUNCTION_NAME, false);
19
20
  await writeHandler(ODB_FUNCTION_NAME, true);
@@ -50,7 +51,7 @@ exports.setupImageFunction = async ({ constants: { INTERNAL_FUNCTIONS_SRC, FUNCT
50
51
  status: 301,
51
52
  }, {
52
53
  from: `${basePath}/${IMAGE_FUNCTION_NAME}/*`,
53
- to: `/.netlify/${ODB_PATH}/${IMAGE_FUNCTION_NAME}`,
54
+ to: `/.netlify/builders/${IMAGE_FUNCTION_NAME}`,
54
55
  status: 200,
55
56
  });
56
57
  if (basePath) {
@@ -1,13 +1,11 @@
1
+ const { existsSync, promises } = require('fs');
1
2
  const path = require('path');
2
- const { yellowBright } = require('chalk');
3
- const { existsSync } = require('fs-extra');
3
+ const { relative } = require('path');
4
+ const { yellowBright, greenBright, blueBright, redBright, reset } = require('chalk');
5
+ const { async: StreamZip } = require('node-stream-zip');
4
6
  const outdent = require('outdent');
7
+ const prettyBytes = require('pretty-bytes');
5
8
  const { satisfies } = require('semver');
6
- exports.verifyBuildTarget = (target) => {
7
- if (target !== 'server') {
8
- console.log(yellowBright `Setting target to ${target} is no longer required. You should check if target=server works for you.`);
9
- }
10
- };
11
9
  // This is when nft support was added
12
10
  const REQUIRED_BUILD_VERSION = '>=18.16.0';
13
11
  exports.verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuild }) => {
@@ -19,25 +17,77 @@ exports.verifyNetlifyBuildVersion = ({ IS_LOCAL, NETLIFY_BUILD_VERSION, failBuil
19
17
  `);
20
18
  }
21
19
  };
20
+ exports.checkForOldFunctions = async ({ functions }) => {
21
+ const oldFunctions = (await functions.list()).filter(({ name }) => name.startsWith('next_'));
22
+ if (oldFunctions.length !== 0) {
23
+ console.log(yellowBright(outdent `
24
+ We have found the following functions in your site that seem to be left over from the old Next.js plugin (v3). We have guessed this because the name starts with "next_".
25
+
26
+ ${reset(oldFunctions.map(({ name }) => `- ${name}`).join('\n'))}
27
+
28
+ If they were created by the old plugin, these functions are likely to cause errors so should be removed. You can do this by deleting the following directories:
29
+
30
+ ${reset(oldFunctions.map(({ mainFile }) => `- ${path.relative(process.cwd(), path.dirname(mainFile))}`).join('\n'))}
31
+ `));
32
+ }
33
+ };
22
34
  exports.checkNextSiteHasBuilt = ({ publish, failBuild }) => {
23
35
  if (!existsSync(path.join(publish, 'BUILD_ID'))) {
24
36
  return failBuild(outdent `
25
37
  The directory "${path.relative(process.cwd(), publish)}" does not contain a Next.js production build. Perhaps the build command was not run, or you specified the wrong publish directory.
26
38
  In most cases it should be set to the site's ".next" directory path, unless you have chosen a custom "distDir" in your Next config.
27
39
  If you are using "next export" then the Essential Next.js plugin should be removed. See https://ntl.fyi/remove-plugin for details.
28
- `);
40
+ `);
29
41
  }
30
42
  if (existsSync(path.join(publish, 'export-detail.json'))) {
31
43
  failBuild(outdent `
32
44
  Detected that "next export" was run, but site is incorrectly publishing the ".next" directory.
33
45
  This plugin is not needed for "next export" so should be removed, and publish directory set to "out".
34
- See https://ntl.fyi/remove-plugin for more details on how to remove this plugin.`);
46
+ See https://ntl.fyi/remove-plugin for more details on how to remove this plugin.
47
+ `);
35
48
  }
36
49
  };
37
50
  exports.checkForRootPublish = ({ publish, failBuild }) => {
38
51
  if (path.resolve(publish) === path.resolve('.')) {
39
52
  failBuild(outdent `
40
53
  Your publish directory is pointing to the base directory of your site. This is not supported for Next.js sites, and is probably a mistake.
41
- In most cases it should be set to ".next", unless you have chosen a custom "distDir" in your Next config, or the Next site is in a subdirectory.`);
54
+ In most cases it should be set to ".next", unless you have chosen a custom "distDir" in your Next config, or the Next site is in a subdirectory.
55
+ `);
56
+ }
57
+ };
58
+ // 50MB, which is the documented max, though the hard max seems to be higher
59
+ const LAMBDA_MAX_SIZE = 1024 * 1024 * 50;
60
+ exports.checkZipSize = async (file, maxSize = LAMBDA_MAX_SIZE) => {
61
+ if (!existsSync(file)) {
62
+ console.warn(`Could not check zip size because ${file} does not exist`);
63
+ return;
64
+ }
65
+ const size = await promises.stat(file).then(({ size }) => size);
66
+ if (size < maxSize) {
67
+ return;
68
+ }
69
+ // We don't fail the build, because the actual hard max size is larger so it might still succeed
70
+ console.log(redBright(outdent `
71
+ The function zip ${yellowBright(relative(process.cwd(), file))} size is ${prettyBytes(size)}, which is larger than the maximum supported size of ${prettyBytes(maxSize)}.
72
+ There are a few reasons this could happen. You may have accidentally bundled a large dependency, or you might have a
73
+ large number of pre-rendered pages included.
74
+ `));
75
+ const zip = new StreamZip({ file });
76
+ console.log(`Contains ${await zip.entriesCount} files`);
77
+ const sortedFiles = Object.values(await zip.entries()).sort((a, b) => b.size - a.size);
78
+ const largest = {};
79
+ for (let i = 0; i < 10 && i < sortedFiles.length; i++) {
80
+ largest[`${i + 1}`] = {
81
+ File: sortedFiles[i].name,
82
+ 'Compressed Size': prettyBytes(sortedFiles[i].compressedSize),
83
+ 'Uncompressed Size': prettyBytes(sortedFiles[i].size),
84
+ };
42
85
  }
86
+ console.log(yellowBright `\n\nThese are the largest files in the zip:`);
87
+ console.table(largest);
88
+ console.log(greenBright `\n\nFor more information on fixing this, see ${blueBright `https://ntl.fyi/large-next-functions`}`);
43
89
  };
90
+ exports.logBetaMessage = () => console.log(greenBright(outdent `
91
+ Thank you for trying the Essential Next.js beta plugin.
92
+ Please share feedback (both good and bad) at ${blueBright `https://ntl.fyi/next-beta-feedback`}
93
+ `));
package/lib/index.js CHANGED
@@ -1,28 +1,36 @@
1
- // @ts-check
2
1
  const { join, relative } = require('path');
3
- const { copy, existsSync } = require('fs-extra');
2
+ const { ODB_FUNCTION_NAME } = require('./constants');
4
3
  const { restoreCache, saveCache } = require('./helpers/cache');
5
4
  const { getNextConfig, configureHandlerFunctions, generateRedirects } = require('./helpers/config');
5
+ const { moveStaticPages, movePublicFiles } = require('./helpers/files');
6
6
  const { generateFunctions, setupImageFunction, generatePagesResolver } = require('./helpers/functions');
7
- const { verifyNetlifyBuildVersion, checkNextSiteHasBuilt, verifyBuildTarget, checkForRootPublish, } = require('./helpers/verification');
7
+ const { verifyNetlifyBuildVersion, checkNextSiteHasBuilt, checkForRootPublish, logBetaMessage, checkZipSize, checkForOldFunctions, } = require('./helpers/verification');
8
+ /** @type import("@netlify/build").NetlifyPlugin */
8
9
  module.exports = {
9
10
  async onPreBuild({ constants, netlifyConfig, utils: { build: { failBuild }, cache, }, }) {
11
+ var _a;
12
+ logBetaMessage();
10
13
  const { publish } = netlifyConfig.build;
11
14
  checkForRootPublish({ publish, failBuild });
12
15
  verifyNetlifyBuildVersion({ failBuild, ...constants });
13
16
  await restoreCache({ cache, publish });
17
+ (_a = netlifyConfig.build).environment || (_a.environment = {});
18
+ // eslint-disable-next-line unicorn/consistent-destructuring
19
+ netlifyConfig.build.environment.NEXT_PRIVATE_TARGET = 'server';
14
20
  },
15
21
  async onBuild({ constants, netlifyConfig, utils: { build: { failBuild }, }, }) {
16
22
  const { publish } = netlifyConfig.build;
17
23
  checkNextSiteHasBuilt({ publish, failBuild });
18
- const { appDir, basePath, i18n, images, target } = await getNextConfig({ publish, failBuild });
19
- verifyBuildTarget(target);
20
- configureHandlerFunctions({ netlifyConfig, publish: relative(process.cwd(), publish) });
24
+ const { appDir, basePath, i18n, images, target, ignore } = await getNextConfig({ publish, failBuild });
25
+ configureHandlerFunctions({ netlifyConfig, ignore, publish: relative(process.cwd(), publish) });
21
26
  await generateFunctions(constants, appDir);
22
27
  await generatePagesResolver({ netlifyConfig, target, constants });
23
- const publicDir = join(appDir, 'public');
24
- if (existsSync(publicDir)) {
25
- await copy(publicDir, `${publish}/`);
28
+ await movePublicFiles({ appDir, publish });
29
+ if (process.env.EXPERIMENTAL_MOVE_STATIC_PAGES) {
30
+ console.log("The flag 'EXPERIMENTAL_MOVE_STATIC_PAGES' is no longer required, as it is now the default. To disable this behavior, set the env var 'SERVE_STATIC_FILES_FROM_ORIGIN' to 'true'");
31
+ }
32
+ if (!process.env.SERVE_STATIC_FILES_FROM_ORIGIN) {
33
+ await moveStaticPages({ target, failBuild, netlifyConfig, i18n });
26
34
  }
27
35
  await setupImageFunction({ constants, imageconfig: images, netlifyConfig, basePath });
28
36
  await generateRedirects({
@@ -31,7 +39,12 @@ module.exports = {
31
39
  i18n,
32
40
  });
33
41
  },
34
- async onPostBuild({ netlifyConfig, utils: { cache } }) {
35
- return saveCache({ cache, publish: netlifyConfig.build.publish });
42
+ async onPostBuild({ netlifyConfig, utils: { cache, functions }, constants: { FUNCTIONS_DIST } }) {
43
+ await saveCache({ cache, publish: netlifyConfig.build.publish });
44
+ await checkForOldFunctions({ functions });
45
+ await checkZipSize(join(FUNCTIONS_DIST, `${ODB_FUNCTION_NAME}.zip`));
46
+ },
47
+ onEnd() {
48
+ logBetaMessage();
36
49
  },
37
50
  };
@@ -1,30 +1,80 @@
1
+ const { promises, existsSync } = require('fs');
1
2
  const { Server } = require('http');
3
+ const { tmpdir } = require('os');
2
4
  const path = require('path');
3
5
  const { Bridge } = require('@vercel/node/dist/bridge');
6
+ const { downloadFile } = require('./handlerUtils');
4
7
  const makeHandler = () =>
5
8
  // We return a function and then call `toString()` on it to serialise it as the launcher function
6
- (conf, app) => {
9
+ // eslint-disable-next-line max-params
10
+ (conf, app, pageRoot, staticManifest = [], mode = 'ssr') => {
11
+ // This is just so nft knows about the page entrypoints. It's not actually used
12
+ try {
13
+ // eslint-disable-next-line node/no-missing-require
14
+ require.resolve('./pages.js');
15
+ }
16
+ catch { }
17
+ // We don't want to write ISR files to disk in the lambda environment
18
+ conf.experimental.isrFlushToDisk = false;
19
+ // Set during the request as it needs the host header. Hoisted so we can define the function once
20
+ let base;
21
+ // Only do this if we have some static files moved to the CDN
22
+ if (staticManifest.length !== 0) {
23
+ // These are static page files that have been removed from the function bundle
24
+ // In most cases these are served from the CDN, but for rewrites Next may try to read them
25
+ // from disk. We need to intercept these and load them from the CDN instead
26
+ // Sadly the only way to do this is to monkey-patch fs.promises. Yeah, I know.
27
+ const staticFiles = new Set(staticManifest);
28
+ // Yes, you can cache stuff locally in a Lambda
29
+ const cacheDir = path.join(tmpdir(), 'next-static-cache');
30
+ // Grab the real fs.promises.readFile...
31
+ const readfileOrig = promises.readFile;
32
+ // ...then money-patch it to see if it's requesting a CDN file
33
+ promises.readFile = async (file, options) => {
34
+ // We only care about page files
35
+ if (file.startsWith(pageRoot)) {
36
+ // We only want the part after `pages/`
37
+ const filePath = file.slice(pageRoot.length + 1);
38
+ // Is it in the CDN and not local?
39
+ if (staticFiles.has(filePath) && !existsSync(file)) {
40
+ // This name is safe to use, because it's one that was already created by Next
41
+ const cacheFile = path.join(cacheDir, filePath);
42
+ // Have we already cached it? We ignore the cache if running locally to avoid staleness
43
+ if ((!existsSync(cacheFile) || process.env.NETLIFY_DEV) && base) {
44
+ await promises.mkdir(path.dirname(cacheFile), { recursive: true });
45
+ // Append the path to our host and we can load it like a regular page
46
+ const url = `${base}/${filePath}`;
47
+ await downloadFile(url, cacheFile);
48
+ }
49
+ // Return the cache file
50
+ return readfileOrig(cacheFile, options);
51
+ }
52
+ }
53
+ return readfileOrig(file, options);
54
+ };
55
+ }
7
56
  let NextServer;
8
57
  try {
9
58
  // next >= 11.0.1. Yay breaking changes in patch releases!
10
59
  NextServer = require('next/dist/server/next-server').default;
11
60
  }
12
- catch {
61
+ catch (error) {
62
+ if (!error.message.includes("Cannot find module 'next/dist/server/next-server'")) {
63
+ // A different error, so rethrow it
64
+ throw error;
65
+ }
13
66
  // Probably an old version of next
14
67
  }
15
- // This is just so nft knows about the page entrypoints
16
- try {
17
- // eslint-disable-next-line node/no-missing-require
18
- require.resolve('./pages.js');
19
- }
20
- catch { }
21
68
  if (!NextServer) {
22
69
  try {
23
70
  // next < 11.0.1
24
71
  // eslint-disable-next-line node/no-missing-require, import/no-unresolved
25
72
  NextServer = require('next/dist/next-server/server/next-server').default;
26
73
  }
27
- catch {
74
+ catch (error) {
75
+ if (!error.message.includes("Cannot find module 'next/dist/next-server/server/next-server'")) {
76
+ throw error;
77
+ }
28
78
  throw new Error('Could not find Next.js server');
29
79
  }
30
80
  }
@@ -46,6 +96,18 @@ const makeHandler = () =>
46
96
  const bridge = new Bridge(server);
47
97
  bridge.listen();
48
98
  return async (event, context) => {
99
+ var _a, _b, _c;
100
+ // Ensure that paths are encoded - but don't double-encode them
101
+ event.path = new URL(event.path, event.rawUrl).pathname;
102
+ // Next expects to be able to parse the query from the URL
103
+ const query = new URLSearchParams(event.queryStringParameters).toString();
104
+ event.path = query ? `${event.path}?${query}` : event.path;
105
+ // Only needed if we're intercepting static files
106
+ if (staticManifest.length !== 0) {
107
+ const { host } = event.headers;
108
+ const protocol = event.headers['x-forwarded-proto'] || 'http';
109
+ base = `${protocol}://${host}`;
110
+ }
49
111
  const { headers, ...result } = await bridge.launcher(event, context);
50
112
  /** @type import("@netlify/functions").HandlerResponse */
51
113
  // Convert all headers to multiValueHeaders
@@ -58,12 +120,17 @@ const makeHandler = () =>
58
120
  multiValueHeaders[key] = [headers[key]];
59
121
  }
60
122
  }
61
- if (multiValueHeaders['set-cookie'] &&
62
- multiValueHeaders['set-cookie'][0] &&
63
- multiValueHeaders['set-cookie'][0].includes('__prerender_bypass')) {
123
+ if ((_b = (_a = multiValueHeaders['set-cookie']) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.includes('__prerender_bypass')) {
64
124
  delete multiValueHeaders.etag;
65
125
  multiValueHeaders['cache-control'] = ['no-cache'];
66
126
  }
127
+ // Sending SWR headers causes undefined behaviour with the Netlify CDN
128
+ const cacheHeader = (_c = multiValueHeaders['cache-control']) === null || _c === void 0 ? void 0 : _c[0];
129
+ if (cacheHeader === null || cacheHeader === void 0 ? void 0 : cacheHeader.includes('stale-while-revalidate')) {
130
+ console.log({ cacheHeader });
131
+ multiValueHeaders['cache-control'] = ['public, max-age=0, must-revalidate'];
132
+ }
133
+ multiValueHeaders['x-render-mode'] = [mode];
67
134
  return {
68
135
  ...result,
69
136
  multiValueHeaders,
@@ -73,13 +140,22 @@ const makeHandler = () =>
73
140
  };
74
141
  const getHandler = ({ isODB = false, publishDir = '../../../.next', appDir = '../../..' }) => `
75
142
  const { Server } = require("http");
143
+ const { tmpdir } = require('os')
144
+ const { promises, existsSync } = require("fs");
76
145
  // We copy the file here rather than requiring from the node module
77
146
  const { Bridge } = require("./bridge");
147
+ const { downloadFile } = require('./handlerUtils')
148
+
78
149
  const { builder } = require("@netlify/functions");
79
150
  const { config } = require("${publishDir}/required-server-files.json")
151
+ let staticManifest
152
+ try {
153
+ staticManifest = require("${publishDir}/static-manifest.json")
154
+ } catch {}
80
155
  const path = require("path");
156
+ const pageRoot = path.resolve(path.join(__dirname, "${publishDir}", config.target === "server" ? "server" : "serverless", "pages"));
81
157
  exports.handler = ${isODB
82
- ? `builder((${makeHandler().toString()})(config, "${appDir}"));`
83
- : `(${makeHandler().toString()})(config, "${appDir}");`}
158
+ ? `builder((${makeHandler().toString()})(config, "${appDir}", pageRoot, staticManifest, 'odb'));`
159
+ : `(${makeHandler().toString()})(config, "${appDir}", pageRoot, staticManifest, 'ssr');`}
84
160
  `;
85
161
  module.exports = getHandler;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.downloadFile = void 0;
7
+ const fs_1 = require("fs");
8
+ const http_1 = __importDefault(require("http"));
9
+ const https_1 = __importDefault(require("https"));
10
+ const stream_1 = require("stream");
11
+ const util_1 = require("util");
12
+ const streamPipeline = (0, util_1.promisify)(stream_1.pipeline);
13
+ const downloadFile = async (url, destination) => {
14
+ console.log(`Downloading ${url} to ${destination}`);
15
+ const httpx = url.startsWith('https') ? https_1.default : http_1.default;
16
+ await new Promise((resolve, reject) => {
17
+ const req = httpx.get(url, { timeout: 10000 }, (response) => {
18
+ if (response.statusCode < 200 || response.statusCode > 299) {
19
+ reject(new Error(`Failed to download ${url}: ${response.statusCode} ${response.statusMessage || ''}`));
20
+ return;
21
+ }
22
+ const fileStream = (0, fs_1.createWriteStream)(destination);
23
+ streamPipeline(response, fileStream)
24
+ .then(resolve)
25
+ .catch((error) => {
26
+ console.log(`Error downloading ${url}`, error);
27
+ reject(error);
28
+ });
29
+ });
30
+ req.on('error', (error) => {
31
+ console.log(`Error downloading ${url}`, error);
32
+ reject(error);
33
+ });
34
+ });
35
+ };
36
+ exports.downloadFile = downloadFile;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netlify/plugin-nextjs",
3
- "version": "4.0.0-beta.1",
3
+ "version": "4.0.0-beta.10",
4
4
  "description": "Run Next.js seamlessly on Netlify",
5
5
  "main": "lib/index.js",
6
6
  "files": [
@@ -10,7 +10,7 @@
10
10
  "scripts": {
11
11
  "build:demo": "next build demo",
12
12
  "cy:open": "cypress open --config-file cypress/config/all.json",
13
- "cy:run": "cypress run --config-file cypress/config/all.json",
13
+ "cy:run": "cypress run --config-file ../cypress/config/ci.json",
14
14
  "dev:demo": "next dev demo",
15
15
  "format": "run-s format:check-fix:*",
16
16
  "format:ci": "run-s format:check:*",
@@ -52,14 +52,19 @@
52
52
  },
53
53
  "homepage": "https://github.com/netlify/netlify-plugin-nextjs#readme",
54
54
  "dependencies": {
55
- "@netlify/functions": "^0.7.2",
55
+ "@netlify/functions": "^0.10.0",
56
56
  "@netlify/ipx": "^0.0.7",
57
57
  "@vercel/node": "^1.11.2-canary.4",
58
58
  "chalk": "^4.1.2",
59
- "destr": "^1.1.0",
60
59
  "fs-extra": "^10.0.0",
60
+ "globby": "^11.0.4",
61
61
  "moize": "^6.1.0",
62
+ "node-fetch": "^2.6.6",
63
+ "node-stream-zip": "^1.15.0",
62
64
  "outdent": "^0.8.0",
65
+ "p-limit": "^3.1.0",
66
+ "pathe": "^0.2.0",
67
+ "pretty-bytes": "^5.6.0",
63
68
  "semver": "^7.3.5",
64
69
  "slash": "^3.0.0",
65
70
  "tiny-glob": "^0.2.9"
@@ -67,18 +72,20 @@
67
72
  "devDependencies": {
68
73
  "@babel/core": "^7.15.8",
69
74
  "@babel/preset-env": "^7.15.8",
70
- "@netlify/eslint-config-node": "^3.3.0",
75
+ "@netlify/build": "^18.25.2",
76
+ "@netlify/eslint-config-node": "^3.3.7",
71
77
  "@testing-library/cypress": "^8.0.1",
78
+ "@types/fs-extra": "^9.0.13",
72
79
  "@types/jest": "^27.0.2",
73
80
  "@types/mocha": "^9.0.0",
74
81
  "babel-jest": "^27.2.5",
75
82
  "cpy": "^8.1.2",
76
- "cypress": "^8.5.0",
83
+ "cypress": "^9.0.0",
77
84
  "eslint-config-next": "^11.0.0",
78
85
  "husky": "^4.3.0",
79
86
  "jest": "^27.0.0",
80
87
  "netlify-plugin-cypress": "^2.2.0",
81
- "next": "^11.1.3-canary.70",
88
+ "next": "^12.0.2",
82
89
  "npm-run-all": "^4.1.5",
83
90
  "prettier": "^2.1.2",
84
91
  "react": "^17.0.1",