Backport middleware chain from master.

Support #insert_before and #insert_after