Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add API config to allow disabling response size warning #34700

Merged
merged 15 commits into from Feb 25, 2022
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/api-routes/api-middlewares.md
Expand Up @@ -68,6 +68,34 @@ export const config = {
}
```

`responseLimit` is automatically enabled, warning when an API routes' response body is over 4MB. This default value is suitable for
[Vercel](https://vercel.com/docs/concepts/limits/overview#serverless-function-payload-size-limit) as well as AWS Lambdas and other serverless deployments.
For large file downloads, pleas refer to [How do I bypass the 5MB body size limit of Vercel Serverless Functions?](https://vercel.com/support/articles/how-to-bypass-vercel-5mb-body-size-limit-serverless-functions)

<!-- limit was changed to 4mb https://github.com/vercel/next.js/pull/26887 but linked article still says 5mb -->

If you are not using Next.js in a serverless environment, and understand the performance implications of not using a CDN or dedicated media host, you can set this limit to false.

```js
export const config = {
api: {
responseLimit: false,
},
}
```

`responseLimit.sizeLimit` is the maximum response size before a warning is displayed. Default is 4mb. (see above)

```js
export const config = {
api: {
responseLimit: {
sizeLimit: '30mb',
},
},
}
```

## Connect/Express middleware support

You can also use [Connect](https://github.com/senchalabs/connect) compatible middleware.
Expand Down
@@ -1,4 +1,4 @@
# API Routes Body Size Limited to 4MB
# API Routes Response Size Limited to 4MB

#### Why This Error Occurred

Expand Down
4 changes: 2 additions & 2 deletions errors/manifest.json
Expand Up @@ -41,8 +41,8 @@
"path": "/errors/amp-export-validation.md"
},
{
"title": "api-routes-body-size-limit",
"path": "/errors/api-routes-body-size-limit.md"
"title": "api-routes-response-size-limit",
"path": "/errors/api-routes-response-size-limit.md"
},
{
"title": "api-routes-static-export",
Expand Down
23 changes: 23 additions & 0 deletions packages/next/compiled/bytes/LICENSE
@@ -0,0 +1,23 @@
(The MIT License)

Copyright (c) 2012-2014 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2015 Jed Watson <jed.watson@me.com>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 changes: 8 additions & 0 deletions packages/next/compiled/bytes/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/next/compiled/bytes/package.json
@@ -0,0 +1 @@
{"name":"bytes","main":"index.js","author":"TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)","license":"MIT"}
10 changes: 2 additions & 8 deletions packages/next/compiled/compression/index.js

Large diffs are not rendered by default.

16 changes: 5 additions & 11 deletions packages/next/compiled/raw-body/index.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions packages/next/package.json
Expand Up @@ -132,6 +132,7 @@
"@types/babel__generator": "7.6.2",
"@types/babel__template": "7.4.0",
"@types/babel__traverse": "7.11.0",
"@types/bytes": "3.1.1",
"@types/ci-info": "2.0.0",
"@types/compression": "0.0.36",
"@types/content-disposition": "0.5.4",
Expand Down Expand Up @@ -168,6 +169,7 @@
"async-sema": "3.0.0",
"babel-plugin-transform-define": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.4.24",
"bytes": "3.1.1",
"browserify-zlib": "0.2.0",
"browserslist": "4.18.1",
"buffer": "5.6.0",
Expand Down
2 changes: 2 additions & 0 deletions packages/next/server/api-utils/index.ts
Expand Up @@ -82,6 +82,8 @@ export function checkIsManualRevalidate(
export const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`
export const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`

export const RESPONSE_LIMIT_DEFAULT = 4 * 1024 * 1024

export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA)
export const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS)

Expand Down
23 changes: 21 additions & 2 deletions packages/next/server/api-utils/node.ts
Expand Up @@ -6,6 +6,7 @@ import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { PreviewData } from 'next/types'

import bytes from 'next/dist/compiled/bytes'
import jsonwebtoken from 'next/dist/compiled/jsonwebtoken'
import { decryptWithSecret, encryptWithSecret } from '../crypto-utils'
import generateETag from 'next/dist/compiled/etag'
Expand All @@ -28,6 +29,7 @@ import {
COOKIE_NAME_PRERENDER_BYPASS,
COOKIE_NAME_PRERENDER_DATA,
SYMBOL_PREVIEW_DATA,
RESPONSE_LIMIT_DEFAULT,
} from './index'

export function tryGetPreviewData(
Expand Down Expand Up @@ -172,6 +174,7 @@ export async function apiResolver(
}
const config: PageConfig = resolverModule.config || {}
const bodyParser = config.api?.bodyParser !== false
const responseLimit = config.api?.responseLimit ?? true
const externalResolver = config.api?.externalResolver || false

// Parsing of cookies
Expand All @@ -198,6 +201,7 @@ export async function apiResolver(
}

let contentLength = 0
const maxContentLength = getMaxContentLength(responseLimit)
const writeData = apiRes.write
const endResponse = apiRes.end
apiRes.write = (...args: any[2]) => {
Expand All @@ -209,9 +213,11 @@ export async function apiResolver(
contentLength += Buffer.byteLength(args[0] || '')
}

if (contentLength >= 4 * 1024 * 1024) {
if (responseLimit && contentLength >= maxContentLength) {
console.warn(
`API response for ${req.url} exceeds 4MB. This will cause the request to fail in a future version. https://nextjs.org/docs/messages/api-routes-body-size-limit`
`API response for ${req.url} exceeds ${bytes.format(
maxContentLength
)}. API Routes are meant to respond quickly. https://nextjs.org/docs/messages/api-routes-response-size-limit`
)
}

Expand Down Expand Up @@ -484,3 +490,16 @@ function setPreviewData<T>(
])
return res
}

function getMaxContentLength(
responseLimit?: { sizeLimit?: number | string } | boolean
) {
if (
responseLimit &&
typeof responseLimit !== 'boolean' &&
responseLimit.sizeLimit
) {
return bytes.parse(responseLimit.sizeLimit)
}
return RESPONSE_LIMIT_DEFAULT
}
9 changes: 9 additions & 0 deletions packages/next/taskfile.js
Expand Up @@ -830,6 +830,14 @@ export async function ncc_babel_bundle_packages(task, opts) {
.target('compiled/babel')
}

// eslint-disable-next-line camelcase
externals['bytes'] = 'next/dist/compiled/bytes'
export async function ncc_bytes(task, opts) {
await task
.source(opts.src || relative(__dirname, require.resolve('bytes')))
.ncc({ packageName: 'bytes', externals })
.target('compiled/bytes')
}
// eslint-disable-next-line camelcase
externals['ci-info'] = 'next/dist/compiled/ci-info'
export async function ncc_ci_info(task, opts) {
Expand Down Expand Up @@ -1628,6 +1636,7 @@ export async function ncc(task, opts) {
'ncc_tty_browserify',
'ncc_vm_browserify',
'ncc_babel_bundle',
'ncc_bytes',
'ncc_ci_info',
'ncc_cli_select',
'ncc_comment_json',
Expand Down
6 changes: 6 additions & 0 deletions packages/next/types/index.d.ts
Expand Up @@ -63,6 +63,12 @@ export type NextPage<P = {}, IP = P> = NextComponentType<NextPageContext, IP, P>
export type PageConfig = {
amp?: boolean | 'hybrid'
api?: {
/**
* Configures or disables body size limit warning. Can take a number or
* any string format supported by `bytes`, for example `1000`, `'500kb'` or
* `'3mb'`.
*/
responseLimit?: { sizeLimit?: number | string } | boolean
ijjk marked this conversation as resolved.
Show resolved Hide resolved
/**
* The byte limit of the body. This is the number of bytes or any string
* format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`.
Expand Down
4 changes: 4 additions & 0 deletions packages/next/types/misc.d.ts
Expand Up @@ -143,6 +143,10 @@ declare module 'next/dist/compiled/babel/core-lib-normalize-opts'
declare module 'next/dist/compiled/babel/core-lib-block-hoist-plugin'
declare module 'next/dist/compiled/babel/core-lib-plugin-pass'

declare module 'next/dist/compiled/bytes' {
import m from 'bytes'
export = m
}
declare module 'next/dist/compiled/ci-info' {
import m from 'ci-info'
export = m
Expand Down
@@ -1,5 +1,5 @@
export default (req, res) => {
for (let i = 0; i <= 5 * 1024 * 1024; i++) {
for (let i = 0; i <= 4 * 1024 * 1024; i++) {
res.write('.')
}
res.end()
Expand Down
@@ -0,0 +1,12 @@
export const config = {
api: {
responseLimit: {
sizeLimit: '5mb',
},
},
}

export default (req, res) => {
let body = '.'.repeat(6 * 1024 * 1024)
res.send(body)
}
@@ -0,0 +1,10 @@
export const config = {
api: {
responseLimit: false,
},
}

export default (req, res) => {
let body = '.'.repeat(4 * 1024 * 1024)
res.send(body)
}
2 changes: 1 addition & 1 deletion test/integration/api-support/pages/api/large-response.js
@@ -1,4 +1,4 @@
export default (req, res) => {
let body = '.'.repeat(5 * 1024 * 1024)
let body = '.'.repeat(4 * 1024 * 1024)
res.send(body)
}
23 changes: 21 additions & 2 deletions test/integration/api-support/test/index.test.js
Expand Up @@ -451,13 +451,32 @@ function runTests(dev = false) {
let res = await fetchViaHTTP(appPort, '/api/large-response')
expect(res.ok).toBeTruthy()
expect(stderr).toContain(
'API response for /api/large-response exceeds 4MB. This will cause the request to fail in a future version.'
'API response for /api/large-response exceeds 4MB. API Routes are meant to respond quickly.'
)

res = await fetchViaHTTP(appPort, '/api/large-chunked-response')
expect(res.ok).toBeTruthy()
expect(stderr).toContain(
'API response for /api/large-chunked-response exceeds 4MB. This will cause the request to fail in a future version.'
'API response for /api/large-chunked-response exceeds 4MB. API Routes are meant to respond quickly.'
)
})

it('should not warn if response body is larger than 4MB with responseLimit config = false', async () => {
let res = await fetchViaHTTP(appPort, '/api/large-response-with-config')
expect(res.ok).toBeTruthy()
expect(stderr).not.toContain(
'API response for /api/large-response-with-config exceeds 4MB. API Routes are meant to respond quickly.'
)
})

it('should warn with configured size if response body is larger than configured size', async () => {
let res = await fetchViaHTTP(
appPort,
'/api/large-response-with-config-size'
)
expect(res.ok).toBeTruthy()
expect(stderr).toContain(
'API response for /api/large-response-with-config-size exceeds 5MB. API Routes are meant to respond quickly.'
)
})

Expand Down
10 changes: 10 additions & 0 deletions yarn.lock
Expand Up @@ -4796,6 +4796,11 @@
resolved "https://registry.yarnpkg.com/@types/braces/-/braces-3.0.1.tgz#5a284d193cfc61abb2e5a50d36ebbc50d942a32b"
integrity sha512-+euflG6ygo4bn0JHtn4pYqcXwRtLvElQ7/nnjDu7iYG56H0+OhCd7d6Ug0IE3WcFpZozBKW2+80FUbv5QGk5AQ==

"@types/bytes@3.1.1":
version "3.1.1"
resolved "https://registry.yarnpkg.com/@types/bytes/-/bytes-3.1.1.tgz#67a876422e660dc4c10a27f3e5bcfbd5455f01d0"
integrity sha512-lOGyCnw+2JVPKU3wIV0srU0NyALwTBJlVSx5DfMQOFuuohA8y9S8orImpuIQikZ0uIQ8gehrRjxgQC1rLRi11w==

"@types/cacheable-request@^6.0.1":
version "6.0.1"
resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.1.tgz#5d22f3dded1fd3a84c0bbeb5039a7419c2c91976"
Expand Down Expand Up @@ -7049,6 +7054,11 @@ bytes@3.1.0, bytes@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6"

bytes@3.1.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.1.tgz#3f018291cb4cbad9accb6e6970bca9c8889e879a"
integrity sha512-dWe4nWO/ruEOY7HkUJ5gFt1DCFV9zPRoJr8pV0/ASQermOZjtq8jMjOprC0Kd10GLN+l7xaUPvxzJFWtxGu8Fg==

cacache@^12.0.2:
version "12.0.3"
resolved "https://registry.yarnpkg.com/cacache/-/cacache-12.0.3.tgz#be99abba4e1bf5df461cd5a2c1071fc432573390"
Expand Down