SAN FRANCISCO—In a ruling that should bolster a law giving social-media companies broad immunity from liability for user-generated content, Twitter Inc. on Friday beat back a lawsuit from families of two American contractors killed in an attack in Jordan inspired by the Islamic State group.

The decision from U.S. District Judge William Orrick III highlights the difficulty plaintiffs face when trying to hold social-media companies liable for allegedly providing material support to terrorists.