Commit 3ee5ec44 authored by Lukáš Huvar's avatar Lukáš Huvar Committed by kodiakhq[bot]

Configuration for body parsing size limit (#7896)

This PR introduces the possibility to change the size of the parsed body. This brings features like:
- Adjusting the size of the incoming message
- Better security 
parent 83a3903f
...@@ -17,6 +17,7 @@ export async function apiResolver( ...@@ -17,6 +17,7 @@ export async function apiResolver(
resolverModule: any resolverModule: any
) { ) {
try { try {
let config: PageConfig = {}
let bodyParser = true let bodyParser = true
if (!resolverModule) { if (!resolverModule) {
res.statusCode = 404 res.statusCode = 404
...@@ -25,7 +26,7 @@ export async function apiResolver( ...@@ -25,7 +26,7 @@ export async function apiResolver(
} }
if (resolverModule.config) { if (resolverModule.config) {
const config: PageConfig = resolverModule.config config = resolverModule.config
if (config.api && config.api.bodyParser === false) { if (config.api && config.api.bodyParser === false) {
bodyParser = false bodyParser = false
} }
...@@ -36,7 +37,12 @@ export async function apiResolver( ...@@ -36,7 +37,12 @@ export async function apiResolver(
setLazyProp({ req, params }, 'query', getQueryParser(req)) setLazyProp({ req, params }, 'query', getQueryParser(req))
// // Parsing of body // // Parsing of body
if (bodyParser) { if (bodyParser) {
req.body = await parseBody(req) req.body = await parseBody(
req,
config.api && config.api.bodyParser && config.api.bodyParser.sizeLimit
? config.api.bodyParser.sizeLimit
: '1mb'
)
} }
res.status = statusCode => sendStatusCode(res, statusCode) res.status = statusCode => sendStatusCode(res, statusCode)
...@@ -59,7 +65,7 @@ export async function apiResolver( ...@@ -59,7 +65,7 @@ export async function apiResolver(
* Parse incoming message like `json` or `urlencoded` * Parse incoming message like `json` or `urlencoded`
* @param req request object * @param req request object
*/ */
export async function parseBody(req: NextApiRequest, limit: string = '1mb') { export async function parseBody(req: NextApiRequest, limit: string | number) {
const contentType = parse(req.headers['content-type'] || 'text/plain') const contentType = parse(req.headers['content-type'] || 'text/plain')
const { type, parameters } = contentType const { type, parameters } = contentType
const encoding = parameters.charset || 'utf-8' const encoding = parameters.charset || 'utf-8'
......
...@@ -4,7 +4,11 @@ ...@@ -4,7 +4,11 @@
export type PageConfig = { export type PageConfig = {
amp?: boolean | 'hybrid' amp?: boolean | 'hybrid'
api?: { api?: {
bodyParser?: boolean /**
* 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'`.
*/
bodyParser?: { sizeLimit?: number | string } | false
} }
experimentalPrerender?: boolean | 'inline' | 'legacy' experimentalPrerender?: boolean | 'inline' | 'legacy'
} }
...@@ -1108,7 +1108,7 @@ Those middlewares are: ...@@ -1108,7 +1108,7 @@ Those middlewares are:
- `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}` - `req.query` - an object containing the [query string](https://en.wikipedia.org/wiki/Query_string). Defaults to `{}`
- `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent - `req.body` - an object containing the body parsed by `content-type`, or `null` if no body is sent
Body parsing is enabled by default. Body parsing is enabled by default with a size limit of `1mb` for the parsed body.
You can opt-out of automatic body parsing if you need to consume it as a `Stream`: You can opt-out of automatic body parsing if you need to consume it as a `Stream`:
```js ```js
...@@ -1124,6 +1124,23 @@ export const config = { ...@@ -1124,6 +1124,23 @@ export const config = {
} }
``` ```
You can adjust size of parsed body by adding `sizeLimit` key to `bodyParser`, supported values are by [bytes](https://github.com/visionmedia/bytes.js) library.
```js
// ./pages/api/my-endpoint.js
export default (req, res) => {
// ...
}
export const config = {
api: {
bodyParser: {
sizeLimit: '1mb',
}
},
}
```
As an added bonus, you can also use any [Micro](https://github.com/zeit/micro) compatible [middleware](https://github.com/amio/awesome-micro)! As an added bonus, you can also use any [Micro](https://github.com/zeit/micro) compatible [middleware](https://github.com/amio/awesome-micro)!
For example, [configuring CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for your API endpoint can be done leveraging `micro-cors`. For example, [configuring CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) for your API endpoint can be done leveraging `micro-cors`.
......
export const config = {
api: {
bodyParser: {
sizeLimit: '5mb'
}
}
}
export default (req, res) => {
res.status(200).json(req.body)
}
...@@ -97,6 +97,18 @@ function runTests (serverless = false) { ...@@ -97,6 +97,18 @@ function runTests (serverless = false) {
expect(data.statusText).toEqual('Body exceeded 1mb limit') expect(data.statusText).toEqual('Body exceeded 1mb limit')
}) })
it('should parse bigger body then 1mb', async () => {
const data = await fetchViaHTTP(appPort, '/api/big-parse', null, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(json)
})
expect(data.status).toEqual(200)
})
it('should parse urlencoded body', async () => { it('should parse urlencoded body', async () => {
const body = { const body = {
title: 'Nextjs', title: 'Nextjs',
......
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