Applying Drupal 8 patches in composer.json

Posted on 19/02/2020

Sooner or later you will encounter an issue in Drupal core or contrib project that has been fixed but the update has not been included in an official release.

Sometimes it can take a long time for updates to be released due to various reasons. Low priority fixes in Drupal core can be postponed quite a bit and some contrib modules can be going through changes in maintainers which will delay the updates.

The most convenient way of applying patches is through composer.json file because the same patch will be re-applied after performing other updates or when you simply re-run composer install.
This of course assumes that you built the project using Composer.

There are three steps you need to do:

  1. Find the patch on drupal.org
  2. Update composer.json in your Drupal root.
  3. Run composer install to apply the patch

This is what you need to add to composer.json:

  1. {
  2.     // [...]
  3.     "extra": {
  4.         // [...]
  5.         "patches": {
  6.             "vendor/project": {
  7.                 "Message describing the patch: https://www.drupal.org/ISSUE_URL": "https://www.drupal.org/url/to/patch/file.patch"
  8.             }
  9.         }
  10.     }
  11. }

UPDATE as noted by Rohit Joshi, patches can be taken out of the root composer.json and stored in a separate file.
This is a cleaner way of listing the patches, especially if you are dealing with many of them.

Here's the code you should use in composer.json instead:

  1. {
  2.     // [...]
  3.     "extra": {
  4.         // [...]
  5.         "patches-file": "composer.patches.json"
  6.     }
  7. }

And then in composer.patches.json:

  1. {
  2.     "patches": {
  3.         "vendor/project": {
  4.             "Message describing the patch": "https://www.drupal.org/url/to/patch/file.patch"
  5.         }
  6.     }
  7. }

UPDATE 2 as noted by Colan Schwartz it is a good practice to include the link to the issue where the patch was submitted. You can always get the node ID from patch URL, but it is easier if you include the link immediately in patch description.