FormData is Unexpected end of JSON input

am having trouble with api route deployed on Vercel. POST request does not handle FormData and return an error: Unexpected end of JSON input. But it works locally on my machine. Request header content type is multipart/form-data; boundary=----formdata-undici-038889596180.

collecting formData:

	const onSubmit = (values: z.infer<typeof SlideSchema>) => {
		const formData = new FormData();

		if (inputFileRef.current?.files?.length) {
			const file = inputFileRef.current.files[0];

			formData.append('files', file, inputFileRef.current.files[0].name);
		}

		// If has new image pass formData
		const data = formData.get('files')
			? {
					...values,
					image: formData,
				}
			: values;

		startTransition(() => {
			if (!imagePreview) {
				toast({
					description: (
						<ToastMessage
							data={{ message: 'Зображення обовязкове!', success: false }}
						/>
					),
				});

				return;
			}

			if (user && imagePreview) {
				handleCreateUpdateMainCarouselSlide(data, user.id!, editMode)
					.then((data) => {
						if (data.success && !editMode) {
							mainForm.reset(defaultValues);
							setImagePreview(null);
						}

						// if (data.success && editMode) mainForm.reset(data.result);

						toast({
							description: <ToastMessage data={data} />,
						});
					})
					.catch((e) => {
						console.log('error', e);
					});
			}
		});
	};

function to upload file:

export const uploadFile = async (
	formData: FormData,
	endpoint: string,
	folder: string,
) => {
	const url = `${getOrigin()}${endpoint}`;

	try {
		const response = await fetch(url, {
			method: 'POST',
			body: formData,
			headers: {
				'X-Upload-Folder': folder,
			},
		});
		const data = await response.json();

		return data;
	} catch (error) {
		console.log('error', error);

		return { errors: [error] };
	}
};

api route that does not work on Vercel:

export async function POST(request: NextRequest) {
	// const folder = request.headers.get('X-Upload-Folder');
	const formData = await request.formData();
	const files = formData.get('files');

	return NextResponse.json({ files });

	// return await uploadFile(request, folder!);
}
1 Like

Hi @gokugoru!

Welcome to the Vercel Community! :smiley:

Have you checked the logs to give you some clues as to why it’s not working when deployed on Vercel? That usually helps get an idea of where to start looking.

1 Like
Error: TypeError: Failed to parse body as FormData.
    at node:internal/deps/undici/undici:4249:27
    at successSteps (node:internal/deps/undici/undici:4288:27)
    at fullyReadBody (node:internal/deps/undici/undici:2724:9)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async consumeBody (node:internal/deps/undici/undici:4297:7)
    at async W (/var/task/.next/server/app/api/upload/route.js:6:9431)
    at async O (/var/task/.next/server/app/api/upload/route.js:6:10328)
    at async /var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:42484
    at async eI.execute (/var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:32486)
    at async eI.handle (/var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:43737)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.