Unverified Commit 62f3f878 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add next.config.js validation with ajv (#38498)

* Add next.config.js validation with ajv

* update manifest

* update lib type

* remove old tests

* update to pre-build validation code

* ensure validate output is ncced

* Apply suggestions from code review
Co-authored-by: 's avatarSteven <steven@ceriously.com>

* Add example of typing next.config.js
Co-authored-by: 's avatarSteven <steven@ceriously.com>
parent 5a15c5fb
# Invalid next.config.js
#### Why This Error Occurred
In your `next.config.js` file you passed invalid options that either are the incorrect type or an unknown field.
#### Possible Ways to Fix It
Fixing the listed config errors will remove this warning. You can also leverage the `NextConfig` type by importing from `next` to help ensure your config is correct.
```ts
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
/* config options here */
}
module.exports = nextConfig
```
### Useful Links
- [`next.config.js`](https://nextjs.org/docs/api-reference/next.config.js/introduction)
......@@ -711,6 +711,10 @@
{
"title": "node-module-in-edge-runtime",
"path": "/errors/node-module-in-edge-runtime.md"
},
{
"title": "invalid-next-config",
"path": "/errors/invalid-next-config.md"
}
]
}
......
/// <reference types="./types/global" />
/// <reference path="./dist/styled-jsx-types/global.d.ts" />
/// <reference path="./amp.d.ts" />
/// <reference path="./app.d.ts" />
/// <reference path="./config.d.ts" />
......@@ -11,7 +12,6 @@
/// <reference path="./router.d.ts" />
/// <reference path="./script.d.ts" />
/// <reference path="./server.d.ts" />
/// <reference path="./dist/styled-jsx-types/global" />
export { default } from './types'
export * from './types'
......@@ -50,6 +50,7 @@
"index.d.ts",
"types/index.d.ts",
"types/global.d.ts",
"types/compiled.d.ts",
"image-types/global.d.ts"
],
"bin": {
......@@ -168,6 +169,7 @@
"@vercel/ncc": "0.33.4",
"@vercel/nft": "0.20.0",
"acorn": "8.5.0",
"ajv": "8.11.0",
"amphtml-validator": "1.0.35",
"arg": "4.1.0",
"assert": "2.0.0",
......
This diff is collapsed.
......@@ -566,3 +566,13 @@ export function isServerRuntime(value?: string): value is ServerRuntime {
value === undefined || value === 'nodejs' || value === 'experimental-edge'
)
}
export function validateConfig(userConfig: NextConfig): {
errors?: Array<any> | null
} {
const configValidator = require('next/dist/next-config-validate.js')
configValidator(userConfig)
return {
errors: configValidator.errors,
}
}
......@@ -12,6 +12,7 @@ import {
normalizeConfig,
ExperimentalConfig,
NextConfigComplete,
validateConfig,
} from './config-shared'
import { loadWebpackHook } from './config-utils'
import {
......@@ -44,23 +45,6 @@ const experimentalWarning = execOnce(
}
)
const missingExperimentalWarning = execOnce(
(configFileName: string, features: string[]) => {
const s = features.length > 1 ? 's' : ''
const dont = features.length > 1 ? 'do not' : 'does not'
const them = features.length > 1 ? 'them' : 'it'
Log.warn(
chalk.bold(
`You have defined experimental feature${s} (${features.join(
', '
)}) in ${configFileName} that ${dont} exist in this version of Next.js.`
)
)
Log.warn(`Please remove ${them} from your configuration.`)
console.warn()
}
)
function assignDefaults(userConfig: { [key: string]: any }) {
const configFileName = userConfig.configFileName
if (typeof userConfig.exportTrailingSlash !== 'undefined') {
......@@ -83,7 +67,6 @@ function assignDefaults(userConfig: { [key: string]: any }) {
}
if (key === 'experimental' && typeof value === 'object') {
const enabledMissingExperiments: string[] = []
const enabledExperiments: (keyof ExperimentalConfig)[] = []
// defaultConfig.experimental is predefined and will never be undefined
......@@ -92,9 +75,7 @@ function assignDefaults(userConfig: { [key: string]: any }) {
for (const featureName of Object.keys(
value
) as (keyof ExperimentalConfig)[]) {
if (!(featureName in defaultConfig.experimental)) {
enabledMissingExperiments.push(featureName)
} else if (
if (
value[featureName] !== defaultConfig.experimental[featureName]
) {
enabledExperiments.push(featureName)
......@@ -102,9 +83,6 @@ function assignDefaults(userConfig: { [key: string]: any }) {
}
}
if (enabledMissingExperiments.length > 0) {
missingExperimentalWarning(configFileName, enabledMissingExperiments)
}
if (enabledExperiments.length > 0) {
experimentalWarning(configFileName, enabledExperiments)
}
......@@ -796,6 +774,16 @@ export default async function loadConfig(
userConfigModule.default || userConfigModule
)
const validateResult = validateConfig(userConfig)
if (validateResult.errors) {
Log.warn(`Invalid next.config.js options detected: `)
console.error(
JSON.stringify(validateResult.errors, null, 2),
'\nSee more info here: https://nextjs.org/docs/messages/invalid-next-config'
)
}
if (Object.keys(userConfig).length === 0) {
Log.warn(
`Detected ${configFileName}, no exported configuration found. https://nextjs.org/docs/messages/empty-configuration`
......
......@@ -176,6 +176,47 @@ export async function ncc_node_fetch(task, opts) {
.target('compiled/node-fetch')
}
// eslint-disable-next-line camelcase
export async function compile_config_schema(task, opts) {
const { configSchema } = require('./dist/server/config-schema')
// eslint-disable-next-line
const Ajv = require('ajv')
// eslint-disable-next-line
const standaloneCode = require('ajv/dist/standalone').default
// eslint-disable-next-line
const ajv = new Ajv({ code: { source: true }, allErrors: true })
ajv.addKeyword({
keyword: 'isFunction',
schemaType: 'boolean',
compile() {
return (data) => data instanceof Function
},
code(ctx) {
const { data } = ctx
ctx.fail(Ajv._`!(${data} instanceof Function)`)
},
metaSchema: {
anyOf: [{ type: 'boolean' }],
},
})
const compiled = ajv.compile(configSchema)
const validateCode = standaloneCode(ajv, compiled)
const preNccFilename = join(__dirname, 'dist', 'next-config-validate.js')
await fs.writeFile(preNccFilename, validateCode)
await task
.source(opts.src || './dist/next-config-validate.js')
.ncc({})
.target('dist/next-config-validate')
await fs.unlink(preNccFilename)
await fs.rename(
join(__dirname, 'dist/next-config-validate/next-config-validate.js'),
join(__dirname, 'dist/next-config-validate.js')
)
await fs.rmdir(join(__dirname, 'dist/next-config-validate'))
}
// eslint-disable-next-line camelcase
externals['acorn'] = 'next/dist/compiled/acorn'
export async function ncc_acorn(task, opts) {
......@@ -1953,7 +1994,7 @@ export async function trace(task, opts) {
}
export async function build(task, opts) {
await task.serial(['precompile', 'compile'], opts)
await task.serial(['precompile', 'compile', 'compile_config_schema'], opts)
}
export default async function (task) {
......
......@@ -468,6 +468,7 @@ importers:
'@vercel/ncc': 0.33.4
'@vercel/nft': 0.20.0
acorn: 8.5.0
ajv: 8.11.0
amphtml-validator: 1.0.35
arg: 4.1.0
assert: 2.0.0
......@@ -660,6 +661,7 @@ importers:
'@vercel/ncc': 0.33.4
'@vercel/nft': 0.20.0
acorn: 8.5.0
ajv: 8.11.0
amphtml-validator: 1.0.35
arg: 4.1.0
assert: 2.0.0
......@@ -6685,6 +6687,15 @@ packages:
require-from-string: 2.0.2
uri-js: 4.2.2
/ajv/8.11.0:
resolution: {integrity: sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==}
dependencies:
fast-deep-equal: 3.1.3
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
uri-js: 4.2.2
dev: true
/alex/9.1.0:
resolution: {integrity: sha512-mlNQ0CBGinzZj1pjiXaSLsihjZ4Kzq0U0EjR+DrZ3IQQfM4pf4OtxHI1agBIiEwv0tQUzimjgTk+5t9iHeT7Vw==}
hasBin: true
......@@ -21921,7 +21932,7 @@ packages:
dev: true
/unset-value/1.0.0:
resolution: {integrity: sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=}
resolution: {integrity: sha512-PcA2tsuGSF9cnySLHTLSh2qrQiJ70mn+r+Glzxv2TWZblxsxCC52BDlZoPCsz7STd9pN7EZetkWZBAvk4cgZdQ==}
engines: {node: '>=0.10.0'}
requiresBuild: true
dependencies:
......@@ -22001,7 +22012,7 @@ packages:
punycode: 2.1.1
/urix/0.1.0:
resolution: {integrity: sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=}
resolution: {integrity: sha512-Am1ousAhSLBeB9cG/7k7r2R0zj50uDRlZHPGbazid5s9rlF1F/QKYObEKSIunSjIOkJZqwRRLpvewjEkM7pSqg==}
deprecated: Please see https://github.com/lydell/urix#deprecated
requiresBuild: true
......
......@@ -113,50 +113,4 @@ describe('Config Experimental Warning', () => {
'You have enabled experimental feature (newNextLinkBehavior) in next.config.mjs.'
)
})
it('should show warning with next.config.js from object with non-exist experimental', async () => {
configFile.write(`
const config = {
experimental: {
foo: true
}
}
module.exports = config
`)
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(
'You have defined experimental feature (foo) in next.config.js that does not exist in this version'
)
})
it('should show warning with next.config.mjs from object with non-exist experimental', async () => {
configFileMjs.write(`
const config = {
experimental: {
foo: true
}
}
export default config
`)
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(
'You have defined experimental feature (foo) in next.config.mjs that does not exist in this version'
)
})
it('should show warning with next.config.js from object with multiple non-exist experimental', async () => {
configFile.write(`
const config = {
experimental: {
foo: true,
bar: false
}
}
module.exports = config
`)
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(
'You have defined experimental features (foo, bar) in next.config.js that do not exist in this version'
)
})
})
export default function Page() {
return <p>index page</p>
}
import path from 'path'
import { nextBuild } from 'next-test-utils'
import fs from 'fs-extra'
const nextConfigPath = path.join(__dirname, '../next.config.js')
describe('next.config.js validation', () => {
it.each([
{
name: 'invalid config types',
configContent: `
module.exports = {
swcMinify: 'hello',
rewrites: true,
images: {
loader: 'something'
}
}
`,
outputs: [
'/images/loader',
'must be equal to one of the allowed values',
'imgix',
'/rewrites',
'must pass \\"isFunction\\" keyword validation',
'/swcMinify',
'must be boolean',
],
},
{
name: 'unexpected config fields',
configContent: `
module.exports = {
nonExistent: true,
experimental: {
anotherNonExistent: true
}
}
`,
outputs: [
'nonExistent',
'must NOT have additional properties',
'anotherNonExistent',
'must NOT have additional properties',
],
},
])(
'it should validate correctly for $name',
async ({ outputs, configContent }) => {
await fs.writeFile(nextConfigPath, configContent)
const result = await nextBuild(path.join(__dirname, '../'), undefined, {
stderr: true,
stdout: true,
})
await fs.remove(nextConfigPath)
for (const output of outputs) {
expect(result.stdout + result.stderr).toContain(output)
}
}
)
})
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