reactjsform-datajoihapi

Hapi route validation with Joi for Form Data


I have a use case where I need to send an array of files to my Hapi backend. The best way I found to do this from my React client is using FormData. This approach has been working great while on an older version of Hapi and Joi ("hapi": "^17.8.1", "joi": "^13.7.0"). However, after upgraded my Hapi and Joi ("@hapi/hapi": "^20.2.1", "joi": "^17.5.0") I'm having an issue with Joi rejecting the files array with "files[]" must be an array. Any idea why this would be happening now after updating? I have tried using Joi.object as the payload validation but that also gave the same result.

Below is my form data code:

const form = new FormData();

form.append('title', this.state.title);

this.state.files && this.state.files.map((item) => {
   form.append("files[]", item.file);
   return true;
});

Below is my Hapi Route:

{
    method: 'POST',
    path: '/files',
    handler: files.save,
    options: {
        auth: 'jwt',
        validate: {
            payload: {
                title: Joi.string().required(),
                files: Joi.array().items(Joi.any())
            }
        },
        payload: {
            maxBytes: 1048576 * 100,
            output: 'stream',
            parse: true,
            timeout: 60000,
            multipart: true
        }
    }
}

Solution

  • You have to use allow: 'multipart/form-data', and after your code update the object payload should look like this.

    payload: {
            maxBytes: 1048576 * 100,
            output: 'stream',
            parse: true,
            timeout: 60000,
            multipart: true,
            allow: 'multipart/form-data',
        }