Unverified Commit 079c6291 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

experimental: remove legacy plugin system (#20759)

* chore: remove old plugins implementation

* chore: remove `onErrorMiddleware`

* Reduce allowed middleware

* remove collect plugins file

* remove old tests

* remove old demo packages
parent cce82cd7
{
"name": "@next/plugin-google-analytics",
"version": "10.1.4-canary.15",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-plugin-google-analytics"
},
"nextjs": {
"name": "Google Analytics",
"required-env": [
"NEXT_PUBLIC_GA_TRACKING_ID"
]
},
"peerDependencies": {
"next": "*",
"react": "*"
}
}
# Unstable @next/plugin-google-analytics
This package is still very experimental and should not be used at this point
import React from 'react'
export default async function headTags() {
return (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_TRACKING_ID}');
`,
}}
/>
</>
)
}
export default async function initClient({ router }) {
router.events.on('routeChangeComplete', (url) => {
setTimeout(() => {
window.gtag('config', process.env.NEXT_PUBLIC_GA_TRACKING_ID, {
page_location: url,
page_title: document.title,
})
}, 0)
})
}
{
"name": "@next/plugin-sentry",
"version": "10.1.4-canary.15",
"repository": {
"url": "vercel/next.js",
"directory": "packages/next-plugin-sentry"
},
"nextjs": {
"name": "Sentry",
"required-env": [
"SENTRY_DSN",
"SENTRY_RELEASE"
]
},
"peerDependencies": {
"next": "*"
},
"dependencies": {
"@sentry/browser": "5.7.1",
"@sentry/node": "5.7.1"
}
}
# Unstable @next/plugin-sentry
This package is still very experimental and should not be used at this point
import * as Sentry from '@sentry/browser'
export default async function onErrorClient({ err }) {
Sentry.captureException(err)
}
import * as Sentry from '@sentry/node'
export default async function onErrorServer({ err }) {
Sentry.captureException(err)
}
import * as Sentry from '@sentry/browser'
export default async function initClient() {
// by default `@sentry/browser` is configured with defaultIntegrations
// which capture uncaughtExceptions and unhandledRejections
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE,
})
}
import * as Sentry from '@sentry/node'
export default async function initServer() {
// by default `@sentry/node` is configured with defaultIntegrations
// which capture uncaughtExceptions and unhandledRejections
// see here for more https://github.com/getsentry/sentry-javascript/blob/46a02209bafcbc1603c769476ba0a1eaa450759d/packages/node/src/sdk.ts#L22
Sentry.init({
dsn: process.env.SENTRY_DSN,
release: process.env.SENTRY_RELEASE,
})
}
import findUp from 'next/dist/compiled/find-up'
import { promises } from 'fs'
import path from 'path'
import { execOnce } from '../../next-server/lib/utils'
const { version } = require('next/package.json')
export type PluginMetaData = {
requiredEnv: string[]
middleware: string[]
pluginName: string
directory: string
pkgName: string
version: string
config?: { [name: string]: any }
}
// currently supported middleware
export const VALID_MIDDLEWARE = [
'document-head-tags-server',
'on-init-client',
'on-init-server',
'on-error-client',
'on-error-server',
'babel-preset-build',
]
type ENV_OPTIONS = { [name: string]: string }
const exitWithError = (error: string) => {
console.error(error)
process.exit(1)
}
async function collectPluginMeta(
env: ENV_OPTIONS,
pluginPackagePath: string,
pluginName: string,
requiredVersion: string
): Promise<PluginMetaData> {
const pkgDir = path.dirname(pluginPackagePath)
const pluginPackageJson = require(pluginPackagePath)
const pluginMetaData: {
name: string
'required-env': string[]
} = pluginPackageJson.nextjs
if (pluginPackageJson.version !== requiredVersion) {
exitWithError(
`Next.js plugin versions must match the Next.js version being used, received ${pluginName}@${pluginPackageJson.version} need ${requiredVersion}`
)
}
if (!pluginMetaData) {
exitWithError(
`Next.js plugins need to have a "nextjs" key in package.json for ${pluginName}`
)
}
if (!pluginMetaData.name) {
exitWithError(
`Next.js plugins need to have a "nextjs.name" key in package.json for ${pluginName}`
)
}
// TODO: add error link explaining requirements
let middleware: string[] = []
try {
middleware = (
await promises.readdir(path.join(pkgDir, 'src'), { withFileTypes: true })
)
.filter((dirent) => dirent.isFile())
.map((file) => file.name)
} catch (err) {
if (err.code !== 'ENOENT') {
console.error(err)
}
exitWithError(
`Failed to read src/ directory for Next.js plugin: ${pluginName}`
)
}
// remove the extension from the middleware
middleware = middleware.map((item) => {
const parts = item.split('.')
parts.pop()
return parts.join('.')
})
const invalidMiddleware: string[] = []
for (const item of middleware) {
if (!VALID_MIDDLEWARE.includes(item)) {
invalidMiddleware.push(item)
}
}
if (invalidMiddleware.length > 0) {
console.error(
`Next.js Plugin: ${pluginName} listed invalid middleware ${invalidMiddleware.join(
', '
)}`
)
}
// TODO: investigate requiring plugins' env be prefixed
// somehow to prevent collision
if (!Array.isArray(pluginMetaData['required-env'])) {
exitWithError(
'Next.js plugins need to have a "nextjs.required-env" key in package.json'
)
}
const missingEnvFields: string[] = []
for (const field of pluginMetaData['required-env']) {
if (typeof env[field] === 'undefined') {
missingEnvFields.push(field)
}
}
if (missingEnvFields.length > 0) {
exitWithError(
`Next.js Plugin: ${pluginName} required env ${missingEnvFields.join(
', '
)} but was missing in your \`next.config.js\``
)
}
return {
middleware,
directory: pkgDir.replace(/\\/g, '/'),
requiredEnv: pluginMetaData['required-env'],
version: pluginPackageJson.version,
pluginName: pluginMetaData.name,
pkgName: pluginPackageJson.name,
}
}
// clean package name so it can be used as variable
export const getPluginId = (pkg: string): string => {
pkg = pkg.replace(/\W/g, '')
if (pkg.match(/^[0-9]/)) {
pkg = `_${pkg}`
}
return pkg
}
type PluginConfig =
| string
| {
name: string
config: { [name: string]: any }
}
async function _collectPlugins(
dir: string,
env: ENV_OPTIONS,
pluginsConfig: PluginConfig[] | undefined
): Promise<PluginMetaData[]> {
let nextPluginNames: string[] = []
const skippedPluginNames: string[] = []
const hasPluginConfig = Array.isArray(pluginsConfig)
const nextPluginConfigNames = hasPluginConfig
? pluginsConfig!.map((config) =>
typeof config === 'string' ? config : config.name
)
: null
const rootPackageJsonPath = await findUp('package.json', { cwd: dir })
if (!rootPackageJsonPath && !nextPluginConfigNames) {
console.log('Failed to load plugins, no package.json')
return []
}
if (rootPackageJsonPath) {
const rootPackageJson = require(rootPackageJsonPath)
let dependencies: string[] = []
if (rootPackageJson.dependencies) {
dependencies = dependencies.concat(
Object.keys(rootPackageJson.dependencies)
)
}
if (rootPackageJson.devDependencies) {
dependencies = dependencies.concat(
Object.keys(rootPackageJson.devDependencies)
)
}
// find packages with the naming convention
// @next/plugin-[name]
const filteredDeps = dependencies.filter((name) => {
return name.match(/^@next\/plugin/)
})
if (nextPluginConfigNames) {
for (const dep of filteredDeps) {
if (!nextPluginConfigNames.includes(dep)) {
skippedPluginNames.push(dep)
}
}
nextPluginNames = nextPluginConfigNames
} else {
nextPluginNames = filteredDeps
}
}
const nextPluginMetaData = await Promise.all(
nextPluginNames.map((name) =>
collectPluginMeta(
env,
require.resolve(path.join(name, 'package.json'), { paths: [dir] }),
name,
version
)
)
)
for (const plugin of nextPluginMetaData) {
// Add plugin config from `next.config.js`
if (hasPluginConfig) {
const curPlugin = pluginsConfig!.find(
(config) =>
config && typeof config === 'object' && config.name === plugin.pkgName
)
if (curPlugin && typeof curPlugin === 'object') {
plugin.config = curPlugin.config
}
}
console.log(
`Loaded plugin: ${plugin.pkgName}${
plugin.version ? `@${plugin.version}` : ''
}`
)
}
if (skippedPluginNames.length) {
console.log(
`Plugins config used skipped loading: ${skippedPluginNames.join(', ')}`
)
}
console.log()
return nextPluginMetaData
}
// only execute it once between server/client configs
// since the plugins need to match
export const collectPlugins = execOnce(_collectPlugins)
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import ReactRefreshWebpackPlugin from '@next/react-refresh-utils/ReactRefreshWebpackPlugin' import ReactRefreshWebpackPlugin from '@next/react-refresh-utils/ReactRefreshWebpackPlugin'
import chalk from 'chalk'
import crypto from 'crypto' import crypto from 'crypto'
import { readFileSync, realpathSync } from 'fs' import { readFileSync, realpathSync } from 'fs'
import chalk from 'chalk' import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame'
import semver from 'next/dist/compiled/semver' import semver from 'next/dist/compiled/semver'
import path from 'path' import { isWebpack5, webpack } from 'next/dist/compiled/webpack/webpack'
import { webpack, isWebpack5 } from 'next/dist/compiled/webpack/webpack' import path, { join as pathJoin, relative as relativePath } from 'path'
import { import {
DOT_NEXT_ALIAS, DOT_NEXT_ALIAS,
NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT,
...@@ -14,29 +14,25 @@ import { ...@@ -14,29 +14,25 @@ import {
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { getPackageVersion } from '../lib/get-package-version' import { getPackageVersion } from '../lib/get-package-version'
import { CustomRoutes } from '../lib/load-custom-routes.js'
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration'
import { import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS, CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK, CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
REACT_LOADABLE_MANIFEST, REACT_LOADABLE_MANIFEST,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
SERVER_DIRECTORY, SERVER_DIRECTORY,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
} from '../next-server/lib/constants' } from '../next-server/lib/constants'
import { execOnce } from '../next-server/lib/utils' import { execOnce } from '../next-server/lib/utils'
import { NextConfig } from '../next-server/server/config'
import { findPageFile } from '../server/lib/find-page-file' import { findPageFile } from '../server/lib/find-page-file'
import { WebpackEntrypoints } from './entries' import { WebpackEntrypoints } from './entries'
import * as Log from './output/log' import * as Log from './output/log'
import {
collectPlugins,
PluginMetaData,
VALID_MIDDLEWARE,
} from './plugins/collect-plugins'
import { build as buildConfiguration } from './webpack/config' import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration' import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import BuildStatsPlugin from './webpack/plugins/build-stats-plugin' import BuildStatsPlugin from './webpack/plugins/build-stats-plugin'
import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin' import ChunkNamesPlugin from './webpack/plugins/chunk-names-plugin'
...@@ -55,9 +51,6 @@ import WebpackConformancePlugin, { ...@@ -55,9 +51,6 @@ import WebpackConformancePlugin, {
ReactSyncScriptsConformanceCheck, ReactSyncScriptsConformanceCheck,
} from './webpack/plugins/webpack-conformance-plugin' } from './webpack/plugins/webpack-conformance-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin' import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { NextConfig } from '../next-server/server/config'
import { relative as relativePath, join as pathJoin } from 'path'
import { CustomRoutes } from '../lib/load-custom-routes.js'
type ExcludesFalse = <T>(x: T | false) => x is T type ExcludesFalse = <T>(x: T | false) => x is T
...@@ -203,28 +196,11 @@ export default async function getBaseWebpackConfig( ...@@ -203,28 +196,11 @@ export default async function getBaseWebpackConfig(
isDevFallback?: boolean isDevFallback?: boolean
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
let plugins: PluginMetaData[] = []
let babelPresetPlugins: { dir: string; config: any }[] = []
const hasRewrites = const hasRewrites =
rewrites.beforeFiles.length > 0 || rewrites.beforeFiles.length > 0 ||
rewrites.afterFiles.length > 0 || rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0 rewrites.fallback.length > 0
if (config.experimental.plugins) {
plugins = await collectPlugins(dir, config.env, config.plugins)
pluginLoaderOptions.plugins = plugins
for (const plugin of plugins) {
if (plugin.middleware.includes('babel-preset-build')) {
babelPresetPlugins.push({
dir: plugin.directory,
config: plugin.config,
})
}
}
}
const reactVersion = await getPackageVersion({ cwd: dir, name: 'react' }) const reactVersion = await getPackageVersion({ cwd: dir, name: 'react' })
const hasReactRefresh: boolean = dev && !isServer const hasReactRefresh: boolean = dev && !isServer
const hasJsxRuntime: boolean = const hasJsxRuntime: boolean =
...@@ -263,7 +239,6 @@ export default async function getBaseWebpackConfig( ...@@ -263,7 +239,6 @@ export default async function getBaseWebpackConfig(
cwd: dir, cwd: dir,
// Webpack 5 has a built-in loader cache // Webpack 5 has a built-in loader cache
cache: !isWebpack5, cache: !isWebpack5,
babelPresetPlugins,
development: dev, development: dev,
hasReactRefresh, hasReactRefresh,
hasJsxRuntime, hasJsxRuntime,
...@@ -280,9 +255,6 @@ export default async function getBaseWebpackConfig( ...@@ -280,9 +255,6 @@ export default async function getBaseWebpackConfig(
/next[\\/]dist[\\/]client/, /next[\\/]dist[\\/]client/,
/next[\\/]dist[\\/]pages/, /next[\\/]dist[\\/]pages/,
/[\\/](strip-ansi|ansi-regex)[\\/]/, /[\\/](strip-ansi|ansi-regex)[\\/]/,
...(config.experimental.plugins
? VALID_MIDDLEWARE.map((name) => new RegExp(`src(\\\\|/)${name}`))
: []),
] ]
// Support for NODE_PATH // Support for NODE_PATH
...@@ -876,13 +848,6 @@ export default async function getBaseWebpackConfig( ...@@ -876,13 +848,6 @@ export default async function getBaseWebpackConfig(
return { return {
...(clientEntries ? clientEntries : {}), ...(clientEntries ? clientEntries : {}),
...entrypoints, ...entrypoints,
...(isServer
? {
'init-server.js': 'next-plugin-loader?middleware=on-init-server!',
'on-error-server.js':
'next-plugin-loader?middleware=on-error-server!',
}
: {}),
} }
}, },
watchOptions: { watchOptions: {
...@@ -951,7 +916,6 @@ export default async function getBaseWebpackConfig( ...@@ -951,7 +916,6 @@ export default async function getBaseWebpackConfig(
'next-client-pages-loader', 'next-client-pages-loader',
'next-serverless-loader', 'next-serverless-loader',
'noop-loader', 'noop-loader',
'next-plugin-loader',
'next-style-loader', 'next-style-loader',
].reduce((alias, loader) => { ].reduce((alias, loader) => {
// using multiple aliases to replace `resolveLoader.modules` // using multiple aliases to replace `resolveLoader.modules`
......
...@@ -27,7 +27,6 @@ const customBabelLoader = babelLoader((babel) => { ...@@ -27,7 +27,6 @@ const customBabelLoader = babelLoader((babel) => {
const custom = { const custom = {
isServer: opts.isServer, isServer: opts.isServer,
pagesDir: opts.pagesDir, pagesDir: opts.pagesDir,
babelPresetPlugins: opts.babelPresetPlugins,
development: opts.development, development: opts.development,
hasReactRefresh: opts.hasReactRefresh, hasReactRefresh: opts.hasReactRefresh,
hasJsxRuntime: opts.hasJsxRuntime, hasJsxRuntime: opts.hasJsxRuntime,
...@@ -62,7 +61,6 @@ const customBabelLoader = babelLoader((babel) => { ...@@ -62,7 +61,6 @@ const customBabelLoader = babelLoader((babel) => {
delete loader.cache delete loader.cache
delete loader.distDir delete loader.distDir
delete loader.pagesDir delete loader.pagesDir
delete loader.babelPresetPlugins
delete loader.development delete loader.development
delete loader.hasReactRefresh delete loader.hasReactRefresh
delete loader.hasJsxRuntime delete loader.hasJsxRuntime
...@@ -75,7 +73,6 @@ const customBabelLoader = babelLoader((babel) => { ...@@ -75,7 +73,6 @@ const customBabelLoader = babelLoader((babel) => {
customOptions: { customOptions: {
isServer, isServer,
pagesDir, pagesDir,
babelPresetPlugins,
development, development,
hasReactRefresh, hasReactRefresh,
hasJsxRuntime, hasJsxRuntime,
...@@ -187,13 +184,6 @@ const customBabelLoader = babelLoader((babel) => { ...@@ -187,13 +184,6 @@ const customBabelLoader = babelLoader((babel) => {
}, },
] ]
for (const plugin of babelPresetPlugins) {
require(join(plugin.dir, 'src', 'babel-preset-build.js'))(
options,
plugin.config || {}
)
}
return options return options
}, },
} }
......
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { parse } from 'querystring'
import { PluginMetaData, getPluginId } from '../../plugins/collect-plugins'
export type NextPluginLoaderQuery = {
middleware: string
}
export const pluginLoaderOptions: {
plugins: PluginMetaData[]
} = {
plugins: [],
}
const nextPluginLoader: webpack.loader.Loader = function () {
const { middleware }: NextPluginLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
const plugins = pluginLoaderOptions.plugins.filter((plugin) => {
return plugin.middleware.includes(middleware)
})
const pluginIds: string[] = []
const pluginConfigs: any[] = []
return `
${plugins
.map((plugin) => {
const pluginId = getPluginId(plugin.pkgName)
pluginIds.push(pluginId)
pluginConfigs.push(plugin.config || {})
return `import ${pluginId} from '${plugin.directory}/src/${middleware}'`
})
.join('\n')}
export default function (ctx) {
return Promise.all([${pluginIds
.map((id, idx) => `${id}(ctx, ${JSON.stringify(pluginConfigs[idx])})`)
.join(',')}])
}
`
}
export default nextPluginLoader
...@@ -4,12 +4,7 @@ import { apiResolver } from '../../../../next-server/server/api-utils' ...@@ -4,12 +4,7 @@ import { apiResolver } from '../../../../next-server/server/api-utils'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils' import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
export function getApiHandler(ctx: ServerlessHandlerCtx) { export function getApiHandler(ctx: ServerlessHandlerCtx) {
const { const { pageModule, encodedPreviewProps, pageIsDynamic } = ctx
pageModule,
encodedPreviewProps,
pageIsDynamic,
experimental: { initServer, onError },
} = ctx
const { const {
handleRewrites, handleRewrites,
handleBasePath, handleBasePath,
...@@ -19,8 +14,6 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) { ...@@ -19,8 +14,6 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
return async (req: IncomingMessage, res: ServerResponse) => { return async (req: IncomingMessage, res: ServerResponse) => {
try { try {
await initServer()
// We need to trust the dynamic route params from the proxy // We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values // to ensure we are using the correct values
const trustQuery = req.headers[vercelHeader] const trustQuery = req.headers[vercelHeader]
...@@ -52,12 +45,10 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) { ...@@ -52,12 +45,10 @@ export function getApiHandler(ctx: ServerlessHandlerCtx) {
Object.assign({}, parsedUrl.query, params), Object.assign({}, parsedUrl.query, params),
await pageModule, await pageModule,
encodedPreviewProps, encodedPreviewProps,
true, true
onError
) )
} catch (err) { } catch (err) {
console.error(err) console.error(err)
await onError(err)
// TODO: better error for DECODE_FAILED? // TODO: better error for DECODE_FAILED?
if (err.code === 'DECODE_FAILED') { if (err.code === 'DECODE_FAILED') {
......
...@@ -99,8 +99,6 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -99,8 +99,6 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
*/ */
runtimeConfigSetter runtimeConfigSetter
} }
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
import 'next/dist/next-server/server/node-polyfill-fetch' import 'next/dist/next-server/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}' import routesManifest from '${routesManifest}'
...@@ -123,18 +121,12 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -123,18 +121,12 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
page: "${page}", page: "${page}",
basePath: "${basePath}", basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute}, pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}, encodedPreviewProps: ${encodedPreviewProps}
experimental: {
onError,
initServer,
}
}) })
export default apiHandler export default apiHandler
` `
} else { } else {
return ` return `
import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!'
import 'next/dist/next-server/server/node-polyfill-fetch' import 'next/dist/next-server/server/node-polyfill-fetch'
import routesManifest from '${routesManifest}' import routesManifest from '${routesManifest}'
import buildManifest from '${buildManifest}' import buildManifest from '${buildManifest}'
...@@ -210,11 +202,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -210,11 +202,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
escapedBuildId: "${escapedBuildId}", escapedBuildId: "${escapedBuildId}",
basePath: "${basePath}", basePath: "${basePath}",
pageIsDynamic: ${pageIsDynamicRoute}, pageIsDynamic: ${pageIsDynamicRoute},
encodedPreviewProps: ${encodedPreviewProps}, encodedPreviewProps: ${encodedPreviewProps}
experimental: {
onError,
initServer,
}
}) })
export { renderReqToHTML, render } export { renderReqToHTML, render }
` `
......
...@@ -45,8 +45,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) { ...@@ -45,8 +45,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
assetPrefix, assetPrefix,
canonicalBase, canonicalBase,
escapedBuildId, escapedBuildId,
experimental: { initServer, onError },
} = ctx } = ctx
const { const {
handleLocale, handleLocale,
...@@ -477,7 +475,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) { ...@@ -477,7 +475,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
renderReqToHTML, renderReqToHTML,
render: async function render(req: IncomingMessage, res: ServerResponse) { render: async function render(req: IncomingMessage, res: ServerResponse) {
try { try {
await initServer()
const html = await renderReqToHTML(req, res) const html = await renderReqToHTML(req, res)
if (html) { if (html) {
sendPayload(req, res, html, 'html', { sendPayload(req, res, html, 'html', {
...@@ -487,7 +484,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) { ...@@ -487,7 +484,6 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
} }
} catch (err) { } catch (err) {
console.error(err) console.error(err)
await onError(err)
// Throw the error to crash the serverless function // Throw the error to crash the serverless function
throw err throw err
} }
......
...@@ -58,10 +58,6 @@ export type ServerlessHandlerCtx = { ...@@ -58,10 +58,6 @@ export type ServerlessHandlerCtx = {
canonicalBase: string canonicalBase: string
encodedPreviewProps: __ApiPreviewProps encodedPreviewProps: __ApiPreviewProps
i18n?: NextConfig['i18n'] i18n?: NextConfig['i18n']
experimental: {
initServer: () => Promise<any>
onError: ({ err }: { err: Error }) => Promise<any>
}
} }
export function getUtils({ export function getUtils({
......
...@@ -399,19 +399,6 @@ export default async (opts: { webpackHMR?: any } = {}) => { ...@@ -399,19 +399,6 @@ export default async (opts: { webpackHMR?: any } = {}) => {
isPreview, isPreview,
}) })
// call init-client middleware
if (process.env.__NEXT_PLUGINS) {
// @ts-ignore
// eslint-disable-next-line
import('next-plugin-loader?middleware=on-init-client!')
.then((initClientModule) => {
return initClientModule.default({ router })
})
.catch((initClientErr) => {
console.error('Error calling client-init for plugins', initClientErr)
})
}
const renderCtx: RenderRouteInfo = { const renderCtx: RenderRouteInfo = {
App: CachedApp, App: CachedApp,
initial: true, initial: true,
...@@ -474,20 +461,6 @@ export function renderError(renderErrorProps: RenderErrorProps): Promise<any> { ...@@ -474,20 +461,6 @@ export function renderError(renderErrorProps: RenderErrorProps): Promise<any> {
styleSheets: [], styleSheets: [],
}) })
} }
if (process.env.__NEXT_PLUGINS) {
// @ts-ignore
// eslint-disable-next-line
import('next-plugin-loader?middleware=on-error-client!')
.then((onClientErrorModule) => {
return onClientErrorModule.default({ err })
})
.catch((onClientErrorErr) => {
console.error(
'error calling on-error-client for plugins',
onClientErrorErr
)
})
}
// Make sure we log the error to the console, otherwise users can't track down issues. // Make sure we log the error to the console, otherwise users can't track down issues.
console.error(err) console.error(err)
......
...@@ -25,8 +25,7 @@ export async function apiResolver( ...@@ -25,8 +25,7 @@ export async function apiResolver(
query: any, query: any,
resolverModule: any, resolverModule: any,
apiContext: __ApiPreviewProps, apiContext: __ApiPreviewProps,
propagateError: boolean, propagateError: boolean
onError?: ({ err }: { err: any }) => Promise<void>
): Promise<void> { ): Promise<void> {
const apiReq = req as NextApiRequest const apiReq = req as NextApiRequest
const apiRes = res as NextApiResponse const apiRes = res as NextApiResponse
...@@ -99,7 +98,6 @@ export async function apiResolver( ...@@ -99,7 +98,6 @@ export async function apiResolver(
sendError(apiRes, err.statusCode, err.message) sendError(apiRes, err.statusCode, err.message)
} else { } else {
console.error(err) console.error(err)
if (onError) await onError({ err })
if (propagateError) { if (propagateError) {
throw err throw err
} }
......
...@@ -165,7 +165,6 @@ export default class Server { ...@@ -165,7 +165,6 @@ export default class Server {
distDir: string distDir: string
} }
private compression?: Middleware private compression?: Middleware
private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
private incrementalCache: IncrementalCache private incrementalCache: IncrementalCache
protected router: Router protected router: Router
protected dynamicRoutes?: DynamicRoutes protected dynamicRoutes?: DynamicRoutes
...@@ -252,18 +251,6 @@ export default class Server { ...@@ -252,18 +251,6 @@ export default class Server {
this.router = new Router(this.generateRoutes()) this.router = new Router(this.generateRoutes())
this.setAssetPrefix(assetPrefix) this.setAssetPrefix(assetPrefix)
// call init-server middleware, this is also handled
// individually in serverless bundles when deployed
if (!dev && this.nextConfig.experimental.plugins) {
const initServer = require(join(this.serverBuildDir, 'init-server.js'))
.default
this.onErrorMiddleware = require(join(
this.serverBuildDir,
'on-error-server.js'
)).default
initServer()
}
this.incrementalCache = new IncrementalCache({ this.incrementalCache = new IncrementalCache({
dev, dev,
distDir: this.distDir, distDir: this.distDir,
...@@ -294,9 +281,6 @@ export default class Server { ...@@ -294,9 +281,6 @@ export default class Server {
} }
public logError(err: Error): void { public logError(err: Error): void {
if (this.onErrorMiddleware) {
this.onErrorMiddleware({ err })
}
if (this.quiet) return if (this.quiet) return
console.error(err) console.error(err)
} }
...@@ -1157,8 +1141,7 @@ export default class Server { ...@@ -1157,8 +1141,7 @@ export default class Server {
query, query,
pageModule, pageModule,
this.renderOpts.previewProps, this.renderOpts.previewProps,
false, false
this.onErrorMiddleware
) )
return true return true
} }
......
...@@ -56,13 +56,6 @@ function getDocumentFiles( ...@@ -56,13 +56,6 @@ function getDocumentFiles(
* Commonly used for implementing server side rendering for `css-in-js` libraries. * Commonly used for implementing server side rendering for `css-in-js` libraries.
*/ */
export default class Document<P = {}> extends Component<DocumentProps & P> { export default class Document<P = {}> extends Component<DocumentProps & P> {
static headTagsMiddleware = process.env.__NEXT_PLUGINS
? import(
// @ts-ignore loader syntax
'next-plugin-loader?middleware=document-head-tags-server!'
)
: () => []
/** /**
* `getInitialProps` hook returns the context object with the addition of `renderPage`. * `getInitialProps` hook returns the context object with the addition of `renderPage`.
* `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers * `renderPage` callback executes `React` rendering logic synchronously to support server-rendering wrappers
......
{
"name": "@next/plugin-google-analytics",
"version": "0.0.1",
"nextjs": {
"name": "Google Analytics",
"required-env": [
"GA_TRACKING_ID"
]
},
"peerDependencies": {
"next": "*"
}
}
module.exports = function babelPresetBuild(ctx, config) {
// options.plugins
// options.presets
}
export default async function headTags () {
return (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${
process.env.GA_TRACKING_ID
}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.GA_TRACKING_ID}');
`
}}
/>
</>
)
}
export default async function initClient(ctx, config) {
window.didClientInit = true
window.initClientConfig = config.hello
}
export default async function initServer() {
console.log('hi from init server')
}
\ No newline at end of file
{
"dependencies": {
"@next/plugin-google-analytics": "latest"
}
}
import Link from 'next/link'
import Head from 'next/head'
export default () => (
<>
<Head>
<title>Another | next-plugins</title>
</Head>
<p id="another">Another</p>
<Link href="/">
<a id="to-home">home</a>
</Link>
<Link href="/something">
<a id="to-something">something</a>
</Link>
</>
)
import Link from 'next/link'
import Head from 'next/head'
const Page = () => (
<>
<Head>
<title>Home | next-plugins</title>
</Head>
<p id="home">Home</p>
<Link href="/another">
<a id="to-another">another</a>
</Link>
<Link href="/something">
<a id="to-something">something</a>
</Link>
</>
)
Page.getInitialProps = () => ({})
export default Page
import Link from 'next/link'
import Head from 'next/head'
export default () => (
<>
<Head>
<title>Something | next-plugins</title>
</Head>
<p id="something">something</p>
<Link href="/">
<a id="to-home">home</a>
</Link>
<Link href="/another">
<a id="to-another">another</a>
</Link>
</>
)
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import { version } from 'next/package.json'
import {
findPort,
launchApp,
killApp,
nextBuild,
nextStart,
renderViaHTTP,
File,
check,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
let app
let appPort
let stdout
let stderr
const appDir = join(__dirname, '../app')
const nextConfigPath = join(appDir, 'next.config.js')
function runTests() {
it('should render tha page without error', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/home/)
})
it('should apply headTags from plugin correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
const found = Array.from($('head').children()).find((el) => {
return (el.attribs.src || '').match(/googletagmanager.*?my-tracking-id/)
})
expect(found).toBeTruthy()
})
it('should call clientInit from plugin correctly', async () => {
const browser = await webdriver(appPort, '/')
expect(await browser.eval('window.didClientInit')).toBe(true)
})
it('should list loaded plugins', async () => {
expect(stdout).toMatch(/loaded plugin: @next\/plugin-google-analytics/i)
})
it('should ignore directories in plugins', async () => {
expect(stderr).not.toMatch(/listed invalid middleware/i)
})
}
const pluginPkgJson = new File(
join(appDir, 'node_modules/@next/plugin-google-analytics/package.json')
)
describe('Next.js plugins', () => {
beforeAll(async () => {
pluginPkgJson.replace('0.0.1', version)
})
afterAll(() => pluginPkgJson.restore())
describe('version mismatch error', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
pluginPkgJson.replace(version, '0.0.1')
})
afterAll(async () => {
pluginPkgJson.restore()
pluginPkgJson.replace('0.0.1', version)
await fs.remove(nextConfigPath)
})
it('should show error when plugin version mismatches', async () => {
let output = ''
const handleOutput = (msg) => {
output += msg || ''
}
app = await launchApp(appDir, await findPort(), {
onStdout: handleOutput,
onStderr: handleOutput,
})
try {
await check(
() => output,
/Next\.js plugin versions must match the Next\.js version being used/
)
} finally {
if (app) {
await killApp(app)
}
}
})
})
describe('dev mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
appPort = await findPort()
app = await launchApp(appDir, appPort, {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
})
afterAll(() => killApp(app))
runTests(true)
describe('with plugin config', () => {
beforeAll(async () => {
await killApp(app)
await fs.writeFile(
nextConfigPath,
`
module.exports = {
experimental: {
plugins: true
},
plugins: [
{
name: '@next/plugin-google-analytics',
config: { hello: 'world' }
}
],
env: {
GA_TRACKING_ID: 'my-tracking-id'
}
}`
)
appPort = await findPort()
stdout = ''
stderr = ''
app = await launchApp(appDir, appPort, {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
})
afterAll(() => killApp(app))
it('should disable auto detecting plugins when plugin config is used', async () => {
expect(stdout).toMatch(/loaded plugin: @next\/plugin-google-analytics/i)
})
// TODO: investigate why this fails. Potentially build cache related.
it.skip('should expose a plugins config', async () => {
const browser = await webdriver(appPort, '/')
expect(await browser.eval('window.initClientConfig')).toBe('world')
})
})
})
describe('production mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
const results = await nextBuild(appDir, undefined, {
stdout: true,
stderr: true,
})
stdout = results.stdout
stderr = results.stderr
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
await fs.remove(nextConfigPath)
})
runTests()
})
describe('serverless mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = { target: 'serverless', env: { GA_TRACKING_ID: 'my-tracking-id' }, experimental: { plugins: true } }`
)
const results = await nextBuild(appDir, undefined, {
stdout: true,
stderr: true,
})
stdout = results.stdout
stderr = results.stderr
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
await fs.remove(nextConfigPath)
})
runTests()
})
})
...@@ -49,7 +49,6 @@ const babel = async ( ...@@ -49,7 +49,6 @@ const babel = async (
distDir: path.resolve(dir, '.next'), distDir: path.resolve(dir, '.next'),
pagesDir: path.resolve(dir, 'pages'), pagesDir: path.resolve(dir, 'pages'),
cache: false, cache: false,
babelPresetPlugins: [],
development, development,
hasReactRefresh: Boolean(!isServer && development), hasReactRefresh: Boolean(!isServer && development),
}, },
......
...@@ -2662,65 +2662,6 @@ ...@@ -2662,65 +2662,6 @@
dependencies: dependencies:
any-observable "^0.3.0" any-observable "^0.3.0"
"@sentry/browser@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-5.7.1.tgz#1f8435e2a325d7a09f830065ebce40a2b3c708a4"
dependencies:
"@sentry/core" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/core@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/core/-/core-5.7.1.tgz#3eb2b7662cac68245931ee939ec809bf7a639d0e"
dependencies:
"@sentry/hub" "5.7.1"
"@sentry/minimal" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/hub@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-5.7.1.tgz#a52acd9fead7f3779d96e9965c6978aecc8b9cad"
dependencies:
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
tslib "^1.9.3"
"@sentry/minimal@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/minimal/-/minimal-5.7.1.tgz#56afc537737586929e25349765e37a367958c1e1"
dependencies:
"@sentry/hub" "5.7.1"
"@sentry/types" "5.7.1"
tslib "^1.9.3"
"@sentry/node@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/node/-/node-5.7.1.tgz#94e2fbac94f6cc061be3bc14b22813536c59698d"
dependencies:
"@sentry/core" "5.7.1"
"@sentry/hub" "5.7.1"
"@sentry/types" "5.7.1"
"@sentry/utils" "5.7.1"
cookie "^0.3.1"
https-proxy-agent "^3.0.0"
lru_map "^0.3.3"
tslib "^1.9.3"
"@sentry/types@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/types/-/types-5.7.1.tgz#4c4c1d4d891b6b8c2c3c7b367d306a8b1350f090"
"@sentry/utils@5.7.1":
version "5.7.1"
resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-5.7.1.tgz#cf37ad55f78e317665cd8680f202d307fa77f1d0"
dependencies:
"@sentry/types" "5.7.1"
tslib "^1.9.3"
"@sindresorhus/is@^2.0.0": "@sindresorhus/is@^2.0.0":
version "2.1.0" version "2.1.0"
resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-2.1.0.tgz#6ad4ca610f696098e92954ab431ff83bea0ce13f" resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-2.1.0.tgz#6ad4ca610f696098e92954ab431ff83bea0ce13f"
...@@ -5574,10 +5515,6 @@ cookie@0.4.1: ...@@ -5574,10 +5515,6 @@ cookie@0.4.1:
version "0.4.1" version "0.4.1"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.1.tgz#afd713fe26ebd21ba95ceb61f9a8116e50a537d1" resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.1.tgz#afd713fe26ebd21ba95ceb61f9a8116e50a537d1"
cookie@^0.3.1:
version "0.3.1"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb"
cookiejar@^2.1.0: cookiejar@^2.1.0:
version "2.1.2" version "2.1.2"
resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.2.tgz#dd8a235530752f988f9a0844f3fc589e3111125c" resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.2.tgz#dd8a235530752f988f9a0844f3fc589e3111125c"
...@@ -8458,13 +8395,6 @@ https-proxy-agent@^2.2.0, https-proxy-agent@^2.2.1: ...@@ -8458,13 +8395,6 @@ https-proxy-agent@^2.2.0, https-proxy-agent@^2.2.1:
agent-base "^4.3.0" agent-base "^4.3.0"
debug "^3.1.0" debug "^3.1.0"
https-proxy-agent@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz#b8c286433e87602311b01c8ea34413d856a4af81"
dependencies:
agent-base "^4.3.0"
debug "^3.1.0"
human-signals@^1.1.1: human-signals@^1.1.1:
version "1.1.1" version "1.1.1"
resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3" resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-1.1.1.tgz#c5b1cd14f50aeae09ab6c59fe63ba3395fe4dfa3"
...@@ -10460,10 +10390,6 @@ lru-cache@^4.0.0, lru-cache@^4.0.1: ...@@ -10460,10 +10390,6 @@ lru-cache@^4.0.0, lru-cache@^4.0.1:
pseudomap "^1.0.2" pseudomap "^1.0.2"
yallist "^2.1.2" yallist "^2.1.2"
lru_map@^0.3.3:
version "0.3.3"
resolved "https://registry.yarnpkg.com/lru_map/-/lru_map-0.3.3.tgz#b5c8351b9464cbd750335a79650a0ec0e56118dd"
lz-string@^1.4.4: lz-string@^1.4.4:
version "1.4.4" version "1.4.4"
resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.4.4.tgz#c0d8eaf36059f705796e1e344811cf4c498d3a26" resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.4.4.tgz#c0d8eaf36059f705796e1e344811cf4c498d3a26"
...@@ -15736,7 +15662,7 @@ ts-pnp@^1.1.6: ...@@ -15736,7 +15662,7 @@ ts-pnp@^1.1.6:
version "1.2.0" version "1.2.0"
resolved "https://registry.yarnpkg.com/ts-pnp/-/ts-pnp-1.2.0.tgz#a500ad084b0798f1c3071af391e65912c86bca92" resolved "https://registry.yarnpkg.com/ts-pnp/-/ts-pnp-1.2.0.tgz#a500ad084b0798f1c3071af391e65912c86bca92"
tslib@1.11.1, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: tslib@1.11.1, tslib@^1.8.1, tslib@^1.9.0:
version "1.11.1" version "1.11.1"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.11.1.tgz#eb15d128827fbee2841549e171f45ed338ac7e35" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.11.1.tgz#eb15d128827fbee2841549e171f45ed338ac7e35"
integrity sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA== integrity sha512-aZW88SY8kQbU7gpV19lN24LtXh/yD4ZZg6qieAJDDg+YBsJcSmLGK9QpnUjAKVG/xefmvJGd1WUmfpT/g6AJGA==
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment