Handle file uploads using a GraphQL middleware

Vincent Composieux
4 min readJan 14, 2019

GraphQL is a very interesting implementation so that the fronts of your web applications communicate efficiently with your different backends sources (and aggregate if necessary) and also retrieves the information that will be useful to the application only.

Based on a JSON request system (query or mutation), the entry of the HTTP request to the GraphQL server is of the type application/json.

On client side, I needed to upload (via a mutation) information about media content in order to manage a media library, a media consisting of a title and a source image.

This is where it gets stuck: we’re going to need to make an HTTP POST request of type multipart/form-data containing our meta-data and our source file.

My case and for this article, the GraphQL server is developed here in Go via the library GraphQL-Go but this article can be used for all languages.

There are therefore two steps to be carried out. There are two steps:

  • Add a new scalar type (to be called Upload) at the input of our mutation,
  • Develop middleware to intercept the HTTP POST multipart/form-data request and re-map it for GraphQL.

Declaration of a new scalar type: Upload

--

--

Vincent Composieux

Freelance web architect who loves code and infrastructure. Issue solver around various technologies.