When deploying an application using SvelteKit with amplify-adapter to AWS Amplify, an error occurred during image file upload:
Upload error: SvelteKitError: Content-length of 605227 exceeds limit of 524288 bytes.
A 566KB file was rejected because of a 512KB (524,288 bytes) limit.
Normally in SvelteKit, you can set the body size limit via the BODY_SIZE_LIMIT
environment variable:
# .env
BODY_SIZE_LIMIT=52428800 # 50MB
.env
file ✅Despite correct settings, process.env.BODY_SIZE_LIMIT
was undefined
in the Lambda environment.
SvelteKit handles environment variables as follows:
$env/static/private
- loaded from .env
at build timeprocess.env
- runtime environment variablesIt turned out that $env/static/private
had the value, but process.env
was undefined
.
Inspecting amplify-adapter’s source code (handler.js
):
const body_size_limit = parseInt(env('BODY_SIZE_LIMIT', '524288'));
The env
function, defined in env.js
, reads from process.env
:
function env(name, fallback) {
const prefixed = "" + name;
return prefixed in process.env ? process.env[prefixed] : fallback;
}
bodySizeLimit
option..env
files correctly in Lambda.Directly patch env.js
in amplify-adapter to force BODY_SIZE_LIMIT
to 50MB.
Create patches/env.js
that forces BODY_SIZE_LIMIT
to 50MB (52428800 bytes):
/* global "" */
const expected = new Set([
'SOCKET_PATH',
'HOST',
'PORT',
'ORIGIN',
'XFF_DEPTH',
'ADDRESS_HEADER',
'PROTOCOL_HEADER',
'HOST_HEADER',
'BODY_SIZE_LIMIT',
]);
if ("") {
for (const name in process.env) {
if (name.startsWith("")) {
const unprefixed = name.slice("".length);
if (!expected.has(unprefixed)) {
throw new Error(
`You should change envPrefix (${""}) to avoid conflicts with existing environment variables — unexpectedly saw ${name}`
);
}
}
}
}
/**
* @param {string} name
* @param {any} fallback
*/
function env(name, fallback) {
// Force BODY_SIZE_LIMIT to 50MB
if (name === 'BODY_SIZE_LIMIT') {
return '52428800';
}
const prefixed = "" + name;
return prefixed in process.env ? process.env[prefixed] : fallback;
}
export { env };
In sh/build-for-amplify.sh
, copy the patch after build:
# Copy necessary assets for compute environment
cp .env build/compute/default/.env
cd build/compute/default/
npm i --production
cd -
# Overwrite env.js with patched version forcing BODY_SIZE_LIMIT=50MB
cp patches/env.js build/compute/default/env.js
echo "✅ env.js patched with BODY_SIZE_LIMIT=52428800 (50MB)"
After the patch, uploading a 605KB file succeeded! 🎉
.env
files do not automatically populate process.env
.patches/env.js
if other size limits are needed.Summary: The file upload size limit issue in SvelteKit + amplify-adapter was resolved by understanding the adapter’s internals and directly patching its environment variable handling. This highlighted the importance of grasping differences in environment variable systems.