I'm using Next.js with server actions, and I encountered the following error when trying to send a large payload - (FormData
with an image attachment):
[Error: Body exceeded 2mb limit.
To configure the body size limit for Server Actions, see: ] {
statusCode: 413
}
I tried to catch this error in my server action using a try...catch block, but it doesn't seem to work as expected. Here's what my server action looks like:
'use server';
export async function handleSomeRequest(data: any) {
try {
// Process the data here
} catch (error: any) {
if (error.statusCode === 413) {
// Attempting to catch the "Body exceeded limit" error
return {
error: 'Payload too large. Please reduce the size and try again.',
status: error.statusCode
};
}
// Just return any other errors
return {
error: error?.message || 'An unexpected error occurred:',
status: error.statusCode
}
}
}
However, the error persists on the terminal, and the server doesn't seem to catch it properly. Somehow the error gets thrown before even reaching my server action logic.
Is it possible to catch this error so i can display it on the UI?
Next.js version: 15.1.4
,
Node.js version: 20.18.0
Thanks!
I'm using Next.js with server actions, and I encountered the following error when trying to send a large payload - (FormData
with an image attachment):
[Error: Body exceeded 2mb limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit] {
statusCode: 413
}
I tried to catch this error in my server action using a try...catch block, but it doesn't seem to work as expected. Here's what my server action looks like:
'use server';
export async function handleSomeRequest(data: any) {
try {
// Process the data here
} catch (error: any) {
if (error.statusCode === 413) {
// Attempting to catch the "Body exceeded limit" error
return {
error: 'Payload too large. Please reduce the size and try again.',
status: error.statusCode
};
}
// Just return any other errors
return {
error: error?.message || 'An unexpected error occurred:',
status: error.statusCode
}
}
}
However, the error persists on the terminal, and the server doesn't seem to catch it properly. Somehow the error gets thrown before even reaching my server action logic.
Is it possible to catch this error so i can display it on the UI?
Next.js version: 15.1.4
,
Node.js version: 20.18.0
Thanks!
This error is thrown by your Next.js server since the size of the request body of the request exceeds the allowed body size defined in your server.
Adding a try-catch
to your server action does not work since the error is thrown by the Next.js server before your function is executed
You can configure Next.js to allow a larger body by adjusting the bodySizeLimit
in next.config.js
file (make sure you understand the risk in allowing a larger body size before making the change)