Skip to content

Commit

Permalink
feat: add body parser limit for server actions (#51104)
Browse files Browse the repository at this point in the history
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?
Add configuration options to modify the `bodyParser` size as it used to
be available in Page Router.
### Why?
Server Actions "Error: Body exceeded 1mb limit" cannot be resolved since
the body-parser limit size is hardcoded to `1mb`.
### How?

Closes NEXT-
Fixes #

-->

### What?

Add configuration options to modify the `bodyParser` size as it used to
be available in Page Router for APIs.

```js
export const config = {
  api: {
    responseLimit: false | '8mb' 
  },
}
```

Reference: [API Routes Response Size
Limit](https://nextjs.org/docs/messages/api-routes-response-size-limit)

### Why?

Server Actions "Error: Body exceeded 1mb limit" cannot be resolved since
the body-parser limit size is hardcoded to `1mb`.

```js
// /packages/next/src/server/app-render/action-handler.ts

// ...
const actionData = (await parseBody(req, '1mb')) || ''
// ...
```

Reference:
https://github.com/vercel/next.js/blob/canary/packages/next/src/server/app-render/action-handler.ts#L355
### How?

- Added option "serverActionsLimit" as `SizeLimit` type to
`config-shared.ts`
- Modified `action-handler.ts` to validate `serverActions` &
`serverActionsLimit` options in nextConfig
- Added conditional `serverActionsLimit` value and `1mb` if falsy

**Working on testing**

Fixes #49891 | #51097 | #51099

---------

Co-authored-by: JJ Kasper <jj@jjsweb.site>
Co-authored-by: Shu Ding <g@shud.in>
  • Loading branch information
3 people committed Jun 23, 2023
1 parent 916e21f commit a9870df
Show file tree
Hide file tree
Showing 17 changed files with 222 additions and 6 deletions.
1 change: 1 addition & 0 deletions packages/next/src/build/entries.ts
Expand Up @@ -377,6 +377,7 @@ export function getEdgeServerEntry(opts: {
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
serverActionsSizeLimit: opts.config.experimental.serverActionsSizeLimit,
}

return {
Expand Down
6 changes: 3 additions & 3 deletions packages/next/src/build/webpack-config.ts
Expand Up @@ -773,8 +773,8 @@ export default async function getBaseWebpackConfig(
const hasServerComponents = hasAppDir
const disableOptimizedLoading = true
const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir
const serverActions = !!config.experimental.serverActions && hasAppDir
const bundledReactChannel = serverActions ? '-experimental' : ''
const useServerActions = !!config.experimental.serverActions && hasAppDir
const bundledReactChannel = useServerActions ? '-experimental' : ''

if (isClient) {
if (
Expand Down Expand Up @@ -2418,7 +2418,7 @@ export default async function getBaseWebpackConfig(
appDir,
dev,
isEdgeServer,
useServerActions: serverActions,
useServerActions,
})),
hasAppDir &&
!isClient &&
Expand Down
@@ -1,4 +1,6 @@
import type webpack from 'webpack'
import type { SizeLimit } from '../../../../../types'

import { getModuleBuildInfo } from '../get-module-build-info'
import { WEBPACK_RESOURCE_QUERIES } from '../../../../lib/constants'
import { stringifyRequest } from '../../stringify-request'
Expand All @@ -21,6 +23,7 @@ export type EdgeSSRLoaderQuery = {
incrementalCacheHandlerPath?: string
preferredRegion: string | string[] | undefined
middlewareConfig: string
serverActionsSizeLimit?: SizeLimit
}

/*
Expand Down Expand Up @@ -54,6 +57,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
incrementalCacheHandlerPath,
preferredRegion,
middlewareConfig: middlewareConfigBase64,
serverActionsSizeLimit,
} = this.getOptions()

const middlewareConfig: MiddlewareConfig = JSON.parse(
Expand Down Expand Up @@ -173,6 +177,11 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
reactLoadableManifest,
clientReferenceManifest: ${isServerComponent} ? rscManifest : null,
serverActionsManifest: ${isServerComponent} ? rscServerManifest : null,
serverActionsSizeLimit: ${isServerComponent} ? ${
typeof serverActionsSizeLimit === 'undefined'
? 'undefined'
: JSON.stringify(serverActionsSizeLimit)
} : undefined,
subresourceIntegrityManifest,
config: ${stringifiedConfig},
buildId: ${JSON.stringify(buildId)},
Expand Down
Expand Up @@ -14,6 +14,7 @@ import {
import { SERVER_RUNTIME } from '../../../../lib/constants'
import { PrerenderManifest } from '../../..'
import { normalizeAppPath } from '../../../../shared/lib/router/utils/app-paths'
import { SizeLimit } from '../../../../../types'

export function getRender({
dev,
Expand All @@ -31,6 +32,7 @@ export function getRender({
clientReferenceManifest,
subresourceIntegrityManifest,
serverActionsManifest,
serverActionsSizeLimit,
config,
buildId,
nextFontManifest,
Expand All @@ -51,6 +53,7 @@ export function getRender({
subresourceIntegrityManifest?: Record<string, string>
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest: any
serverActionsSizeLimit?: SizeLimit
appServerMod: any
config: NextConfigComplete
buildId: string
Expand Down Expand Up @@ -85,6 +88,7 @@ export function getRender({
disableOptimizedLoading: true,
clientReferenceManifest,
serverActionsManifest,
serverActionsSizeLimit,
},
renderToHTML,
incrementalCacheHandler,
Expand Down
Expand Up @@ -30,12 +30,14 @@ import {
import { traverseModules, forEachEntryModule } from '../utils'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import { getProxiedPluginState } from '../../build-context'
import { SizeLimit } from '../../../../types'

interface Options {
dev: boolean
appDir: string
isEdgeServer: boolean
useServerActions: boolean
serverActionsSizeLimit?: SizeLimit
}

const PLUGIN_NAME = 'ClientEntryPlugin'
Expand Down Expand Up @@ -151,13 +153,15 @@ export class ClientReferenceEntryPlugin {
appDir: string
isEdgeServer: boolean
useServerActions: boolean
serverActionsSizeLimit?: SizeLimit
assetPrefix: string

constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.isEdgeServer = options.isEdgeServer
this.useServerActions = options.useServerActions
this.serverActionsSizeLimit = options.serverActionsSizeLimit
this.assetPrefix = !this.dev && !this.isEdgeServer ? '../' : ''
}

Expand Down
1 change: 1 addition & 0 deletions packages/next/src/export/index.ts
Expand Up @@ -472,6 +472,7 @@ export default async function exportApp(
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: options.hasAppDir,
hasServerComponents: options.hasAppDir,
serverActionsSizeLimit: nextConfig.experimental.serverActionsSizeLimit,
nextFontManifest: require(join(
distDir,
'server',
Expand Down
7 changes: 6 additions & 1 deletion packages/next/src/server/app-render/action-handler.ts
Expand Up @@ -5,6 +5,7 @@ import type {
ServerResponse,
} from 'http'
import type { WebNextRequest } from '../base-http/web'
import type { SizeLimit } from '../../../types'

import {
ACTION,
Expand Down Expand Up @@ -245,6 +246,7 @@ export async function handleAction({
generateFlight,
staticGenerationStore,
requestStore,
serverActionsSizeLimit,
}: {
req: IncomingMessage
res: ServerResponse
Expand All @@ -258,6 +260,7 @@ export async function handleAction({
}) => Promise<RenderResult>
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
serverActionsSizeLimit?: SizeLimit
}): Promise<undefined | RenderResult | 'not-found'> {
let actionId = req.headers[ACTION.toLowerCase()] as string
const contentType = req.headers['content-type']
Expand Down Expand Up @@ -372,7 +375,9 @@ export async function handleAction({
} else {
const { parseBody } =
require('../api-utils/node') as typeof import('../api-utils/node')
const actionData = (await parseBody(req, '1mb')) || ''

const actionData =
(await parseBody(req, serverActionsSizeLimit ?? '1mb')) || ''

if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
Expand Down
2 changes: 2 additions & 0 deletions packages/next/src/server/app-render/app-render.tsx
Expand Up @@ -156,6 +156,7 @@ export async function renderToHTMLOrFlight(
nextFontManifest,
supportsDynamicHTML,
nextConfigOutput,
serverActionsSizeLimit,
} = renderOpts

const appUsingSizeAdjust = nextFontManifest?.appUsingSizeAdjust
Expand Down Expand Up @@ -1606,6 +1607,7 @@ export async function renderToHTMLOrFlight(
generateFlight,
staticGenerationStore,
requestStore,
serverActionsSizeLimit,
})

if (actionRequestResult === 'not-found') {
Expand Down
11 changes: 10 additions & 1 deletion packages/next/src/server/app-render/types.ts
@@ -1,5 +1,6 @@
import type { LoadComponentsReturnType } from '../load-components'
import type { ServerRuntime } from '../../../types'
import type { ServerRuntime, SizeLimit } from '../../../types'
import { NextConfigComplete } from '../../server/config-shared'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../../build/webpack/plugins/next-font-manifest-plugin'

Expand Down Expand Up @@ -138,6 +139,14 @@ export type RenderOptsPartial = {
originalPathname?: string
isDraftMode?: boolean
deploymentId?: string
loadConfig?: (
phase: string,
dir: string,
customConfig?: object | null,
rawConfig?: boolean,
silent?: boolean
) => Promise<NextConfigComplete>
serverActionsSizeLimit?: SizeLimit
}

export type RenderOpts = LoadComponentsReturnType & RenderOptsPartial
5 changes: 4 additions & 1 deletion packages/next/src/server/base-server.ts
Expand Up @@ -19,7 +19,7 @@ import {
normalizeRepeatedSlashes,
MissingStaticPage,
} from '../shared/lib/utils'
import type { PreviewData, ServerRuntime } from 'next/types'
import type { PreviewData, ServerRuntime, SizeLimit } from 'next/types'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { OutgoingHttpHeaders } from 'http2'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
Expand Down Expand Up @@ -255,6 +255,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
supportsDynamicHTML?: boolean
isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest
serverActionsSizeLimit?: SizeLimit
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
Expand Down Expand Up @@ -1650,6 +1651,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
incrementalCache,
isRevalidate: isSSG,
originalPathname: components.ComponentMod.originalPathname,
serverActionsSizeLimit:
this.nextConfig.experimental.serverActionsSizeLimit,
}
: {}),
isDataReq,
Expand Down
10 changes: 10 additions & 0 deletions packages/next/src/server/config-schema.ts
Expand Up @@ -304,6 +304,16 @@ const configSchema = {
serverActions: {
type: 'boolean',
},
serverActionsSizeLimit: {
oneOf: [
{
type: 'number',
},
{
type: 'string',
},
] as any,
},
extensionAlias: {
type: 'object',
},
Expand Down
6 changes: 6 additions & 0 deletions packages/next/src/server/config-shared.ts
Expand Up @@ -9,6 +9,7 @@ import {
import { SubresourceIntegrityAlgorithm } from '../build/webpack/plugins/subresource-integrity-plugin'
import { WEB_VITALS } from '../shared/lib/utils'
import type { NextParsedUrlQuery } from './request-meta'
import { SizeLimit } from '../../types'

export type NextConfigComplete = Required<NextConfig> & {
images: Required<ImageConfigComplete>
Expand Down Expand Up @@ -281,6 +282,11 @@ export interface ExperimentalConfig {
* Enable `react@experimental` channel for the `app` directory.
*/
serverActions?: boolean

/**
* Allows adjusting body parser size limit for server actions.
*/
serverActionsSizeLimit?: SizeLimit
}

export type ExportPathMap = {
Expand Down
11 changes: 11 additions & 0 deletions packages/next/src/server/config.ts
Expand Up @@ -416,6 +416,17 @@ function assignDefaults(
result.output = 'standalone'
}

if (typeof result.experimental?.serverActionsSizeLimit !== 'undefined') {
const value = parseInt(
result.experimental.serverActionsSizeLimit.toString()
)
if (isNaN(value) || value < 1) {
throw new Error(
'Server Actions Size Limit must be a valid number or filesize format lager than 1MB: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions'
)
}
}

warnOptionHasBeenMovedOutOfExperimental(
result,
'transpilePackages',
Expand Down
2 changes: 2 additions & 0 deletions packages/next/src/server/render.tsx
Expand Up @@ -23,6 +23,7 @@ import type {
GetStaticProps,
PreviewData,
ServerRuntime,
SizeLimit,
} from 'next/types'
import type { UnwrapPromise } from '../lib/coalesced-function'
import type { ReactReadableStream } from './stream-utils/node-web-streams-helper'
Expand Down Expand Up @@ -260,6 +261,7 @@ export type RenderOptsPartial = {
isBot?: boolean
runtime?: ServerRuntime
serverComponents?: boolean
serverActionsSizeLimit?: SizeLimit
customServer?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
images: ImageConfigComplete
Expand Down

0 comments on commit a9870df

Please sign in to comment.