hapi — How to Fix “Unsupported Media Type”

The “unsupported media type“ error occurred while uploading a file to a hapi server. The file is an Excel sheet and at first, it seemed like the content type was the issue. But the problem was the multipart upload which comes with a straightforward fix!

hapi Series Overview

Fixing “Unsupported Media Type” Error

The “Unsupported Media Type" error has a handful of sources. One of them is an invalid request header.

For example an invalid request header may be accept: 'appplication/json' where the word “appplication” includes three “p”. This causes your hapi server to respond with the 415 error because it doesn’t support the header value natively:

Error: Unsupported Media Type  
    at <stacktrace> {
  data: null,
  isBoom: true,
  isServer: false,
  output: {
    statusCode: 415,
    payload: {
      statusCode: 415,
      error: 'Unsupported Media Type',
      message: 'Unsupported Media Type'
    headers: {}
  raw: <Buffer >,
  mime: 'appplication/json'
        notice the tripple "p"

Fixing “Unsupported Media Type” Error for File Uploads

The file upload from the frontend used a multipart/form-data configuration. Also, the content type set in the frontend was multipart/form-data. The missing part was the related multipart: true configuration.

The hapi server supports payload configuration options when defining routes. The route fix for the “unsupported media type“ error is the multipart configuration on your route that handles file uploads:

module.exports = {  
  method: 'POST',
  path: '/file-uploads',
  options: {
    payload: {
      maxBytes: 209715200,
      output: 'file',
      parse: true,
      multipart: true     // <-- this fixed the media type error
    handler: async (request, h) => {
      // handle file upload

      return h.response('File uploaded').code(201)

Adding multipart: true fixed the file upload problems for us!

Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.