What I've learned during developing a headless site

For the development of this site I built a Drupal 8 backend with a Gatsby React frontend. I first used the JSONAPI module to disclose the data from my Drupal backend, and later on I switched to GraphQL module. There are some subtle differences between the modules, with each having their pros and cons.

JSONAPI vs GraphQL

JSONAPI doesn't handle multilingual sites very well, where GraphQL works better. With JSONAPIĀ  you'll need to add an endpoint for each language and filter out the duplicate nodes, GraphQL supports entity translations. JSONAPI supports image queries, while with GraphQL you'll have to put in some more effort (but it'll work eventually). So, based on your requirements you could either choose the one or the other. Both modules require a different plugin in Gatsby; JSONAPI uses gatsby-source-drupal, GraphQL uses gatsby-source-drupal-graphql.

Endpoint

The JSONAPI endpoint offers everything an anonymous user can do on the site. It makes sense, but if you want a tad more, like menu's or webforms, it isn't what you'd want. You could chose to empower the anonymous user with more permissions, but that's not recommended. You are better of adding some form of authentication, which can be done with the key_auth module where you add a key to a given user. Use the key in your Gatsby enviroment and presto: access to all the magic you want.

With GraphQL you're best off using the simple_oauth module. It's a bit more of a hassle to configure, but there is an excellent tutorial on YouTube.

CORS headers

The webform module by default has webform node module installed, which makes it a bit easier to link a webform to a node. In Gatsby the node is retrieved and placed inside a component. I then retrieve the webform, using webform_jsonschema and process it. This didn't work out of the box due to this error: "Reason: CORS header 'Access-Control-Allow-Origin' missing". The solution is copying the default.services.yml file to services.yml and activate the CORS configuration at the bottom of the file. Clear the cache and you're on your way again.

It's not you, it's me

Just before launching the site, I deployed the backend to the production environment and tried to build Gatsby from that. This had some problems, mainly with images. I kept getting errors querying localFile. For some reason, holding me back for some days, I got the error "Cannot query localFile on type file__file". The problem was that Gatsby wasn't able to transfer the files from the backend. In https://backend.web-beest.nl/sites/default/files there's a .htaccess file that conflicted with the server configuration, which blocked the files from being sent to Gatsby. I altered the file, and the build was up and running again. It makes sense that if it worked locally and not remotely, the problem probably lies with the remote and not the code. Or the between keyboard and chair.

back_blog